2012-06-08 113 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