Zend Framework 2 - Rendering CSV data

后端 未结 3 675
名媛妹妹
名媛妹妹 2020-12-18 16:46

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 = $         


        
3条回答
  •  北海茫月
    2020-12-18 17:13

    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!)

提交回复
热议问题