Drupal MySQL to CSV export - easy way

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)

<?php
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);
  }
}
?>


Bookmark and Share

2 comments

Anonymous's picture

Thank you!

It works fine after that $mysql_result is corrected to $result.

Regards.

Janak's picture

Thanks good point! I hadnt noticed that, changed my code above :)

Post new comment

The content of this field is kept private and will not be shown publicly. If you have a Gravatar account, used to display your avatar.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.

More information about formatting options