Created
April 7, 2014 10:20
-
-
Save nickopris/10017828 to your computer and use it in GitHub Desktop.
From db_query result to csv in Drupal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Add Headers | |
drupal_add_http_header('Content-Type', 'text/csv'); | |
drupal_add_http_header('Content-Disposition', 'attachment;filename=name_your_file.csv'); | |
$fp = fopen('php://output', 'w'); | |
$first = TRUE; | |
foreach ($results as $line) { | |
//Gets the line so we can flip it and get the column names | |
$column_names = get_object_vars($line); | |
if ($first) { | |
$field_names = array_flip($column_names); | |
fputcsv($fp, $field_names); | |
$first = FALSE; // Only happens once | |
} | |
// Puts the actual content | |
fputcsv($fp, $column_names); | |
} | |
fclose($fp); | |
drupal_exit(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment