Skip to content

Instantly share code, notes, and snippets.

@alucard001
Created January 18, 2017 03:32
Show Gist options
  • Save alucard001/bb8e468b0331f0911028e8888317936b to your computer and use it in GitHub Desktop.
Save alucard001/bb8e468b0331f0911028e8888317936b to your computer and use it in GitHub Desktop.
PHP CSV for Excel file download
<?php
// Prepare file download
// Special Thanks: https://www.skoumal.net/en/making-utf-8-csv-excel/
$filename = 'some_file_name.csv';
//headers
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Content-Description: File Transfer');
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename='.$filename.';');
header('Content-Transfer-Encoding: binary');
//open file pointer to standard output
$fp = fopen('php://output', 'w');
//add BOM to fix UTF-8 in Excel
fputs($fp, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));
$result = array(
array("A", "B", "C"),
array("D", "E", "F"),
array("G", "H", "I"),
);
if($fp){
$isFirstRow = true;
foreach($result as $row){
// If it is first row, add a column header
if($isFirstRow){
fputcsv($fp, array( 'colA',
'colB',
'colC',
)
);
$isFirstRow = false;
}
// Put data to file
fputcsv($fp, $row);
}
}
fclose($fp);
exit();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment