Fragmented Thought

Writing CSV Files Using Drupal

By

Published:

Lance Gliser

Heads up! This content is more than six months old. Take some time to verify everything still works as expected.

I'm leaving this one here, mostly as a note for myself. I've found too often that samples on the web, and indeed in existing code I inherit are chalked full of 'doing it the hard way' and memory leaks. This is the simplest and cleanest method for handling streaming large amounts of data out to a csv.

function _write_csv(){ $path = 'public://{directory}/{subdirectory}/'; $filename = '{something}-' . REQUEST_TIME . '.csv'; // Ensure the directory if( !file_prepare_directory($path, FILE_CREATE_DIRECTORY) ){ drupal_set_message( t('Unable to create directory in file system. Check permissions and try again.'), 'error' ); return; } // Ensure the file $file = file_save_data('', $path . $filename); if( !$file ){ drupal_set_message( t('Unable to write to file system. Check permissions and try again.'), 'error' ); return; } // Stream data - This is a simplified example. Better to do it in a batch if you have a high volume of data $fh = fopen($file->uri, 'w'); if( !$fh ){ drupal_set_message( t('Unable open file for writing. Check permissions and try again.'), 'error' ); return; } fputcsv($fh, array( 'Column 1', 'Column 2', )); for($i = 0; $i < 3; ++$i){ fputcsv($fh, array( 'Column 1 - ' . $i, 'Column 2 - ' . $i, )); } fclose($fh); // Notify the filesystem of the size change $file->filesize = filesize($file->uri); file_save($file); // Tell the user where we stuck it drupal_set_message( t('Export complete. <a href="!url">!filename</a>.', array( '!url' => file_create_url($file->uri), '!filename' => $filename, ))); }