Skip to content

Instantly share code, notes, and snippets.

@nickopris
Created April 7, 2014 10:20
Show Gist options
  • Save nickopris/10017828 to your computer and use it in GitHub Desktop.
Save nickopris/10017828 to your computer and use it in GitHub Desktop.
From db_query result to csv in Drupal
// 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