Skip to content

Instantly share code, notes, and snippets.

@marcelotorres
Created January 15, 2017 13:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save marcelotorres/5b75b3634fcea20dc7934415563b16ed to your computer and use it in GitHub Desktop.
Save marcelotorres/5b75b3634fcea20dc7934415563b16ed to your computer and use it in GitHub Desktop.
<?php
/**
** convert input array to a csv file and force downlaod the same
**
** should be called before any output is send to the browser
** input array should be an associative array
** the key of the associative array will be first row of the csv file
**
** @link http://perials.com/php-function-convert-array-csv-file-download/ Original post - Php function to convert an array to CSV file for download
** @param array $array
** @return null
**/
function array_to_csv_download(array $array) {
if (count($array) == 0) {
return null;
}
$filename = "data_export_" . date("Y-m-d") . ".csv";
// disable caching
$now = gmdate("D, d M Y H:i:s");
header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
header("Last-Modified: {$now} GMT");
// force download
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
// disposition / encoding on response body
header("Content-Disposition: attachment;filename={$filename}");
header("Content-Transfer-Encoding: binary");
$df = fopen("php://output", 'w');
fputcsv($df, array_keys(reset($array)));
foreach ($array as $row) {
fputcsv($df, $row);
}
fclose($df);
die();
}
<?php
$array_recordset = array(
array('id'=>'560','name'=>'John','age'=>'31','occupation'=>'Designer'),
array('id'=> '561','name'=>'Robert','age'=>'21','occupation'=>'Student')
);
array_to_csv_download($array_recordset);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment