PHP Output Array to CSV with Headers
I had the need in one of my applications to take associative PHP arrays and generate CSV files for the users to download from them. More specifically, I was dumping data from my database to CSV files. However, another thing I wanted to avoid doing was that I did not want to save a file to the web server then have to delete it when the request was done.
This function takes in an array of associative arrays (associative arrays must contain all the same keys) and outputs it to a CSV file using the first row's key values as the headers for the CSV file.
The function looks something like this:
/**
* 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();
}
And here's an example of the function call in use:
$data = array(
array( 'item' => 'Server', 'cost' => 10000, 'approved by' => 'Joe'),
array( 'item' => 'Mt Dew', 'cost' => 1.25, 'approved by' => 'John')
array( 'item' => 'IntelliJ IDEA', 'cost' => 500, 'approved by' => 'James'),
);
outputCsv('expenses.csv', $data);
Hope you guys find this helpful. I know it has become one of my most universal scripts that I put in my applications and it also doubles as an excellent debugging tool for var dumping large arrays into an easy format to read, search, and sort.