【发布时间】:2018-08-17 10:18:12
【问题描述】:
我目前正在 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 内容作为响应文本。
你有什么想法吗? 提前致谢。
【问题讨论】:
-
也许您的 CSV 格式无效,请尝试在生成的文件中替换另一个 100% 有效的 CSV。
-
我已经尝试过这种方法。我刚刚发现如果您向下载器发布请求,zend 会发送错误的下载标头。因此,通过直接下载链接,下载工作......
标签: php download zend-framework2 export-to-csv