Zend Framework 2 - Rendering CSV data

后端 未结 3 698
名媛妹妹
名媛妹妹 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:22

    This is based off the answer provided by Rob.

    In Rob's answer, by assigning $response->getHeaders() to a new $headers variable, then applying the ->addHeaderLine to that new variable, it does not properly set the headers on the $response. So when returned, the headers were not attached to the response.

    To fix this, simply add the headers directly to the $response shown below:

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

提交回复
热议问题