Skip to content

Instantly share code, notes, and snippets.

@wujku
Created January 27, 2016 11:33
Show Gist options
  • Save wujku/9d06e162fedf5cffae78 to your computer and use it in GitHub Desktop.
Save wujku/9d06e162fedf5cffae78 to your computer and use it in GitHub Desktop.
Simple CSV creator for Symfony Framework
<?php
use Symfony\Component\HttpFoundation\StreamedResponse;
/**
* @param $array
* @param $columns ['path.to.value' => 'Column name', 'path.val' => 'Col 2']
* @param $filename
* @return StreamedResponse
*/
function generateCSV($array, $columns, $filename)
{
$response = new StreamedResponse();
$response->setCallback(function() use ($array, $columns) {
$handle = fopen('php://output', 'w');
fputcsv($handle, array_values($columns), ',');
foreach ($array as $row) {
$fileRow = [];
foreach ($columns as $path => $name) {
$fileRow[] = $this->getByPath($row, $path);
}
fputcsv($handle, $fileRow, ',');
}
fclose($handle);
});
$response->setStatusCode(200);
$response->headers->set('Content-Type', 'text/csv; charset=utf-8');
$response->headers->set('Content-Disposition',"attachment; filename=\"{$filename}.csv\"");
return $response;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment