Skip to content

Instantly share code, notes, and snippets.

@daithi-coombes
Forked from magickatt/gist:6130199
Last active August 29, 2015 14:05
Show Gist options
  • Save daithi-coombes/b03b71fe0c577f27c406 to your computer and use it in GitHub Desktop.
Save daithi-coombes/b03b71fe0c577f27c406 to your computer and use it in GitHub Desktop.
<?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