Download a excel file through Zend-Collection of common programming errors

I need to give download excel files stored on server. But I am unable to find an example for download in ZF2. I am trying for the following code

$response = new Response();
$response->getHeaders()->addHeaders(array(
    'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'Content-Disposition' => 'attachment;filename="forecast_template.xlsx"',
    'Cache-Control' => 'max-age=0',
));
$response->setContent(file_get_contents($xlsx_file_name));

But it did not work. I tried setRawBody but that gave error for undefined method. Also I tried “echo $response”, But that just dump string output for headers + binary data.

  1. Using MVC, you can start a file download by short-circuiting the MvcEvent (to do this, just return the Response instance instead of a ViewModel).

    The following example snippet works for me:

    use Zend\Http\Headers;
    
    (...)
    
    $response = $this->getEvent()->getResponse();
    $response->setHeaders(Headers::fromString("Content-Type: application/octet-stream\r\nContent-Length: 9\r\nContent-Disposition: attachment; filename=\"blamoo.txt\""));
    
    $response->setContent('blablabla');
    
    return $response;
    

Originally posted 2013-11-09 23:14:33.