Drupal MySQL to CSV export - easy way

Submitted by Janak on Thu, 06/04/2009 - 13:26

Today I attempted to export MySQL data from Drupal into a CSV file, easy enough, I thought to myself...

After battling for hours trying to do the pesky character escapes and string manipulation, I came across some very handy code in the Views Bonus Pack CSV Export module.

If you are using the views module, this addon is very handy indeed and will save you many hours of manual labour..

Here is a slightly modified version that can be used in any custom module (for instance when you are not using the excellent Views module)

function export_to_excel($result,  $filename = 'myfile.csv'){ 
  drupal_set_header('Content-Type: text/csv');
  drupal_set_header('Content-Disposition: attachment; filename=' . $filename);
 
  $count = mysql_num_fields($result);  
  for($i = 0; $i < $count; $i++){
    $header[] = mysql_field_name($result, $i);
  }
  print implode(',', $header) ."\r\n";
 
  while($row = db_fetch_array($result)){
    foreach($row as $value){
      $values[] = '"' . str_replace('"', '""', decode_entities(strip_tags($value))) . '"'; 
    }
    print implode(',', $values) ."\r\n";
    unset($values);
  }
}