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
















2 comments
22nd Feb, 10
Thank you!
It works fine after that $mysql_result is corrected to $result.
Regards.
22nd Feb, 10
Thanks good point! I hadnt noticed that, changed my code above :)
Post new comment