2012-06-08 71 views
3

我在我的网页上有一个链接,用于下载我在服务器上生成的.CSV文件。下载代码如下:带有内容处理的PHP文件下载问题:附件

//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文件。

任何想法为什么会发生?

+1

你确定没有其他代码被回显出来吗? – ku6pk

+2

'application/excel'应该是['text/csv'](http://www.rfc-editor.org/rfc/rfc4180.txt)。 – Quentin

+0

您可能在php.ini中启用了HTML错误。 –

回答

4

如果这个代码是在控制器的行动,我认为这是因为使用的是ZF,那么你需要禁用布局和视图渲染器,因为它会尝试渲染视图。

尝试:

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);告诉视图渲染不渲染的控制器动作可能包含一些HTML或视图脚本空白。

+0

啊,我怎么错过了?主要道具给你! – scott80109

-4

试试这个:

header("Content-type: application/octet-stream"); 
header("Content-disposition:attachment; filename=inventoryData.csv"); 
+0

怎么会降低?即时通讯使用此代码将近一年,现在我的网站下载CSV文件,它永远不会给我一个错误。 – sephoy08

+0

如何使用不同的,不太有用的内容类型来阻止将HTML数据添加到输出中? – Quentin

+0

你是什么意思先生? – sephoy08

-3

这应该做的伎俩

header("Pragma: public"); 
    header("Expires: 0"); 
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
    header("Cache-Control: private",false); 
    header("Content-Type: application/octet-stream"); 
    header("Content-Disposition: attachment; filename=\"inventoryData.csv\";"); 
    header("Content-Transfer-Encoding: binary"); 
+0

如何更改HTTP标头以停止将HTTP数据前置到HTTP正文中? – Quentin