Writing CSV Files Using Drupal

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.

  1. function _write_csv(){
  2.   $path = 'public://{directory}/{subdirectory}/';
  3.   $filename = '{something}-' . REQUEST_TIME . '.csv';
  4.   // Ensure the directory
  5.   if( !file_prepare_directory($path, FILE_CREATE_DIRECTORY) ){
  6.     drupal_set_message( t('Unable to create directory in file system. Check permissions and try again.'), 'error' );
  7.     return;
  8.   }
  9.   // Ensure the file
  10.   $file = file_save_data('', $path . $filename);
  11.   if( !$file ){
  12.     drupal_set_message( t('Unable to write to file system. Check permissions and try again.'), 'error' );
  13.     return;
  14.   }
  15.   // Stream data - This is a simplified example. Better to do it in a batch if you have a high volume of data
  16.   $fh = fopen($file->uri, 'w');
  17.   if( !$fh ){
  18.     drupal_set_message( t('Unable open file for writing. Check permissions and try again.'), 'error' );
  19.     return;
  20.   }
  21.   fputcsv($fh, array(
  22.     'Column 1',
  23.     'Column 2',
  24.   ));
  25.   for($i = 0; $i < 3; ++$i){
  26.     fputcsv($fh, array(
  27.       'Column 1 - ' . $i,
  28.       'Column 2 - ' . $i,
  29.     ));
  30.   }
  31.   fclose($fh);
  32.   // Notify the filesystem of the size change
  33.   $file->filesize = filesize($file->uri);
  34.   file_save($file);
  35.   // Tell the user where we stuck it
  36.   drupal_set_message( t('Export complete. <a href="!url">!filename</a>.', array(
  37.     '!url' => file_create_url($file->uri),
  38.     '!filename' => $filename,
  39.   )));
  40. }
Tags: 

Comments

Worked like a charm!

This was very helpful. Thanks!

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.