Created
January 15, 2017 13:32
-
-
Save marcelotorres/5b75b3634fcea20dc7934415563b16ed to your computer and use it in GitHub Desktop.
Converter um Array para arquivo CSV em PHP - http://www.marcelotorresweb.com/converter-um-array-para-arquivo-csv-em-php/
This file contains 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 | |
/** | |
** 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(); | |
} |
This file contains 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 | |
$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