Skip to content

Instantly share code, notes, and snippets.

Last active September 19, 2022 23:42
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Output CSV to browser
// 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)
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");
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".

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