wujku
1/27/2016 - 11:33 AM

Simple CSV creator for Symfony Framework

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;
}