Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@danbower 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

This comment has been minimized.

Copy link

@lordspace lordspace commented Mar 30, 2019

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