Zend 框架 CSV 下载

Zend Framework CSV download

我目前正在 Zend Framwork 中开发 CSV 生成器。此时我可以在服务器端创建一个有效的 CSV 文件,现在我想下载该文件。我目前正在使用以下代码:

$reader = new \PHPExcel_Reader_CSV();
$reader->setReadDataOnly(true);

$excel = $reader->load($file); //$file = Path of the csv file in the local storage

$writer = \PHPExcel_IOFactory::createWriter($excel, 'CSV');

$path = 'public/download';
$fileName = 'test.csv';

$writer->save($path . '/' . $fileName);

$response = new ResponseStream();
$response->setStream(fopen($path . '/' . $fileName, 'r'));

$headers = new Headers();
$headers->addHeaders([
    'Content-Type' => [
        'application/force-download',
        'application/octet-stream',
        'application/download'
    ],
    'Content-Length' => filesize($path . '/' . $fileName),
    'Content-Disposition' => 'attachment;filename=' . $fileName,
    'Cache-Control' => 'must-revalidate',
    'Pragma' => 'no-cache',
    'Expires' => 'Thu, 1 Jan 1970 00:00:00 GMT'
]);

$response->setHeaders($headers);

$cookie = new SetCookie('downloadComplete', 'true', time() + 60 * 60, '/');
$response->getHeaders()->addHeader($cookie);

$response->setContent($writer);

return $response;

现在的问题是我只收到 Zend 错误弹出窗口:

statusCode 200 thrownError SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 21 of the JSON data

并将我的 CSV 内容作为响应文本。

你有什么想法吗? 提前致谢。

经过大量调查,我发现下载只有在我们通过 zend 向下载操作发送 Post 请求时才会失败(我假设它会覆盖 self-setted headers ).因此,我通过 java 脚本重定向 ($viewModel->addScriptBlock('window.location = "Your URL";');) 发送了请求并且成功了。