How to Generate a CSV File in Drupal

Submitted by Daniel Henry on 06/05/2013 - 10:04:am

Haven’t dug up this snippet since I discovered views View Data Export but I keep it in my back pocket just in case. It originally served it’s purpose to export data from a custom module I created to store large amounts of statistical data. The client wanted to regularly import and export the information and their was enough of it that I didn’t want the overhead of a node and it’s many hooks and joins. Records is just an array of arrays with the first entry being the table headers. It’s so simple but I keep it around because I can never seem to remember the right syntax or function names for reading and writing files. I spend all my time communicating with databases.

  1. // Output into a csv file
  2. $csv_file = fopen('test.csv', 'w') or die('Cant open file!');
  3. foreach( $records as $offset => $record) {
  4.   fputcsv($csv_file, $record, ',', '"');
  5. }
  6. fclose($csv_file);