Search code examples
csvzend-framework2

Zend Framework 2 - Rendering CSV data


i have a model that returns car data with id, name, price etc. So i have a car controller and a csv action that fetches this data from a model:

$carTable = $this->getServiceLocator()->get('Application\Model\DbTable\Cars');
$cars = $carTable->fetchAll();

i need to download this "$cars" data as a CSV file, so the user can store it on the disk.

I have tried to disable the layout and echo a CSV string and setting "content-type" and other headers, but it didn't work out of the box. Then i figured out that i should probably create a custom CsvRenderer and register it in configuration.

Since i couldn't find any documentation about this on the ZF2 site or in blogs and Stackoverflow answers, i would like to know if this is the recommended general approach for downloading data as CSV in ZF2? or is there a simpler solution that i am not aware of?

Thanks


Solution

  • One solution would be to return a Response object directly from the controller.

    Something like this stands a good chance of working:

    public function downloadAction()
    {
        // magically create $content as a string containing CSV data
    
        $response = $this->getResponse();
        $headers = $response->getHeaders();
        $headers->addHeaderLine('Content-Type', 'text/csv');
        $headers->addHeaderLine('Content-Disposition', "attachment; filename=\"my_filen.csv\"");
        $headers->addHeaderLine('Accept-Ranges', 'bytes');
        $headers->addHeaderLine('Content-Length', strlen($content));
    
        $response->setContent($content);
        return $response;
    }
    

    (Note that I haven't tested this code, but have updated in line with comment!)