2009-07-28 27 views
4

我看到這個帖子了,但它並沒有真正提供一個解決方案(已經至少對我來說工作)...PHP MySQL的導出爲CSV - 結果顯示HTML

我有一個PHP頁面它執行一些基本的MySQL查詢,其結果顯示在頁面上。我在整個過程中使用了一些$ _GET和$ _SESSION變量。

在同一頁面中,我還允許用戶「導出到CSV」(通過調用函數)。從導出返回的文件底部有CSV結果,但也包含我的頁面的HTML(它調用函數)。

現在,在頁面頂部,我有ob_start()和底部我有ob_flush(),否則在頁面加載時,我將收到一些「無法修改標題...」錯誤。所以,正如在帖子中建議,我讀了:

My guess is that you've got some sort of template that generates the same HTML header and footer regardless of the page that is requested. Sometime before the exportCSV function is called, the header is generated. 

You don't show the bottom of the output, but I'll bet the footer is there too, since I suspect the flow control will continue on to that code after the function exits." 

(http://stackoverflow.com/questions/207019/why-am-i-getting-html-in-my-mysql-export-to-csv/207046) 

有沒有人有任何想法,我如何能夠防止這種情況發生?讓我知道如果我應該發佈我的一些代碼,我會...

謝謝!

編輯:

當調用ob_end_clean()之前,我打電話給我的導出功能,它擺脫了CSV之前的任何HTML的。不過,我仍然得到一些HTML結束標記的CSV結果之後......

fname lname MONTH WeekdayCount WeekendCount 
John Doe 8 1 0 
John Doe 7 3 2 
Jane Smith 7 3 2 
</div>    
    </div>   
</div>    

</body>     

</html>    

編輯:

這個問題已經通過調用調用CSV導出腳本後退出()來解決。

回答

8

在輸出csv數據之前,您可以嘗試調用ob_end_clean(),它應該丟棄已經打印爲HTML的任何輸出。

您可以在輸出您的csv數據後調用exit()以停止正在打印的其餘頁面。

這似乎不是一個特別好的方法,你能不能有一個單獨的PHP腳本來輸出默認不包含頁眉和頁腳的csv嗎?

+0

感謝您的建議,請參閱我的編輯.. – littleK 2009-07-29 00:30:05

2

如果沒有看到您的腳本,很難說出什麼問題,除非您發送ANY內容後不能發送HTTP標頭到客戶端。這包括空白。有時候,在開始<?php聲明之前,您還將擁有不可打印的字符。如有必要,使用十六進制編輯器來查找這些。

您export.php腳本的頂部應該是這個樣子:

<?php 
header('Content-Type: text/csv'); 
... 

是這種情況?

+0

cletus, 不,這不是這種情況。但我加了它,它似乎沒有做任何事情... – littleK 2009-07-29 00:31:48

0

我也面臨這個問題,並已解決它。 我的代碼是:

<html> 
<title> </title> 
<body> 
     <?php 
     ....Code which output MySQL to CSV 
     ?> 
</body></html> 

下面是例子在頂部與HTML代碼出來CSV文件。

<html>      
<head>     
<meta http-equiv="Content-Language" content="th">     
<meta http-equiv="content-Type" content="text/html; charset=window-874">      
<meta http-equiv="content-Type" content="text/html; charset=tis-620">     

<title> Super Man </title>     

</head>      

<body bgcolor="#FFFFD4">      

<SQL rows resulted> 
xx5497 1/7/2015 1:03 SSFTM SSFTVM 35 Condition2 
xx5498 1/7/2015 1:04 SSDHN SSDHKN 13 Condition2 
xx5499 1/7/2015 1:06 SSFTM SSFTVM 14 Condition2 

運行時,CSV文件的頂部有前12行。它對我來說看起來很瘋狂。我通過將PHP代碼移到頂端來解決它。那麼結果是OK。只有SQL結果輸出到CSV文件。

<?php 
    ....Code which output MySQL to CSV 
?> 

<html> 
<title> </title> 
<body> 

</body></html>