Last active
September 19, 2022 23:42
-
-
Save magickatt/6130199 to your computer and use it in GitHub Desktop.
Output CSV to browser
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
<?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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
header("Content-Disposition: attachment filename=\"$filename.csv\";" );
should beheader("Content-Disposition: attachment; filename=\"$filename.csv\";" );
. Note the semi-colon after "attachment".