2009-07-28 68 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>