我的网页上有一个链接,用于下载我在服务器上生成的 .CSV 文件。下载代码如下:
//open/save dialog box
header('Content-Disposition: attachment; filename="inventoryData.csv"');
//content type
header('Content-type: application/excel');
//read from server and write to buffer
readfile('spreadsheet/inventory.csv');
当我打开服务器上的文件时,它看起来很好。但是,当我通过对话框下载文件时,它会将网页的 HTML 代码添加到 .csv 文件中。
知道为什么会这样吗?
最佳答案
如果此代码位于 Controller 操作中,我认为这是因为您使用的是 ZF,那么您需要禁用布局和 View 渲染器,因为它将尝试渲染 View 。
尝试:
public function downloadAction()
{
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
//...
//open/save dialog box
header('Content-Disposition: attachment; filename="inventoryData.csv"');
//content type
header('Content-type: application/excel');
//read from server and write to buffer
readfile('spreadsheet/inventory.csv');
}
$this->_helper->layout()->disableLayout();
阻止渲染你的布局脚本(假设你使用布局),并且 $this->_helper->viewRenderer->setNoRender(true);
告诉 View 渲染器不要渲染可能包含一些 HTML 或空格的 Controller 操作的 View 脚本。
关于php - 带有 Content-Disposition : attachment 的 PHP 中的文件下载问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10946077/