Zend Framework 2 - Rendering CSV data

后端 未结 3 652
名媛妹妹
名媛妹妹 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!)

    0 讨论(0)
  • 2020-12-18 17:15

    Since we are talking about ZF2, I would rather solve this by adding a new CSV ViewStrategy/Renderer/ViewModel.

    Here you can read more about implementing own rendering and response strategies: Zend Docs

    or even here: http://zend-framework-community.634137.n4.nabble.com/ZF2-Implementing-custom-renderer-strategy-td4655896.html

    That will turn the code in the controller slimmer, cleaner and more clear, since you don't have to care about the headers in the controller, but in the renderer. Then, each time you need a new CSV output, you don't have to write that action all over again, you just use the CSV View model

    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
提交回复
热议问题