Skip to content

Instantly share code, notes, and snippets.

@AucT
Forked from jaydeepakbari/php-array-to-csv.php
Created December 16, 2020 08:06
Show Gist options
  • Save AucT/da311f2633ef5a6c977152f48f72fa7b to your computer and use it in GitHub Desktop.
Save AucT/da311f2633ef5a6c977152f48f72fa7b to your computer and use it in GitHub Desktop.
<?php
/**
* Takes in a filename and an array associative data array and outputs a csv file
* @param string $fileName
* @param array $assocDataArray
*/
public function outputCsv($fileName, $assocDataArray)
{
ob_clean();
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: text/csv');
header('Content-Disposition: attachment;filename=' . $fileName);
if(isset($assocDataArray['0'])){
$fp = fopen('php://output', 'w');
fputcsv($fp, array_keys($assocDataArray['0']));
foreach($assocDataArray AS $values){
fputcsv($fp, $values);
}
fclose($fp);
}
ob_flush();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment