Skip to content

Instantly share code, notes, and snippets.

@magickatt
Last active September 19, 2022 23:42
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save magickatt/6130199 to your computer and use it in GitHub Desktop.
Save magickatt/6130199 to your computer and use it in GitHub Desktop.
Output CSV to browser
<?php
// Headings and rows
$headings = array('ID', 'Name', 'Colour');
$array = array(
array(1, 'Apple', 'Green'),
array(2, 'Banana', 'Yellow'),
array(3, 'Orange', 'Orange'),
);
// Open the output stream
$fh = fopen('php://output', 'w');
// Start output buffering (to capture stream contents)
ob_start();
fputcsv($fh, $headings);
// Loop over the * to export
if (! empty($array)) {
foreach ($array as $item) {
fputcsv($fh, $item);
}
}
// Get the contents of the output buffer
$string = ob_get_clean();
$filename = 'csv_' . date('Ymd') .'_' . date('His');
// Output CSV-specific headers
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment filename=\"$filename.csv\";" );
header("Content-Transfer-Encoding: binary");
exit($string);
@danbower
Copy link

danbower commented Feb 6, 2015

header("Content-Disposition: attachment filename=\"$filename.csv\";" ); should be header("Content-Disposition: attachment; filename=\"$filename.csv\";" );. Note the semi-colon after "attachment".

@lordspace
Copy link

Yep. @danbower Without that semi-colon I was getting download as the current file

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment