Skip to content

Instantly share code, notes, and snippets.

@i-am-chitti
Created April 21, 2023 20:29
Show Gist options
  • Save i-am-chitti/1d1f2ded2a0fd80a4b30d1bbb0deae80 to your computer and use it in GitHub Desktop.
Save i-am-chitti/1d1f2ded2a0fd80a4b30d1bbb0deae80 to your computer and use it in GitHub Desktop.
Export Script with batch processing using WP_FileSystem, streaming and buffering
global $wp_filesystem;
// If not already set, initialize the WP filesystem.
if ( empty( $wp_filesystem ) ) {
require_once ABSPATH . '/wp-admin/includes/file.php';
WP_Filesystem();
}
$uploads_dir = wp_get_upload_dir()['basedir'] . '/movie-library/';
if ( ! $wp_filesystem->is_dir( $uploads_dir ) ) {
$wp_filesystem->mkdir( $uploads_dir );
}
$file_path = $uploads_dir . $file_name;
// If output file doesn't exists, create it.
if ( ! $wp_filesystem->exists( $file_path ) ) {
$wp_filesystem->touch( $file_path );
}
ob_start();
$output_stream = fopen( 'php://output', 'w' );
fputcsv( $output_stream, $header_row );
forEach($batches as $batch) {
$movie_data = get_movie_data();
fputcsv( $output_stream, $movie_data );
}
fclose( $output_stream );
$wp_filesystem->put_contents( $file_path, ob_get_clean() ); // final IO
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment