繁体   English   中英

PHP将MySQL导出为CSV - 显示HTML的结果

[英]PHP Export MySQL to CSV - Results showing 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。 但是,在CSV结果后,我仍然会收到一些HTML结束标记...

 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导出脚本后调用exit()解决了此问题。

您可以在输出csv数据之前尝试调用ob_end_clean(),它应该丢弃您已经打印为HTML的任何输出。

您可以在输出csv数据后调用exit()以停止打印其余页面。

这似乎不是一个特别好的方法,您是否可以没有单独的PHP脚本来输出默认情况下不包含页眉和页脚的csv?

在没有看到您的脚本的情况下,除了说您在发送任何内容后无法向客户端发送HTTP标头之外,很难说出问题究竟是什么。 这包括空白区域。 有时你在打开<?php语句之前会有不可打印的字符。 如有必要,使用十六进制编辑器来查找这些。

export.php脚本的顶部应如下所示:

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

是这样的吗?

我也面临这个问题并且已经解决了。 我的代码是:

<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代码移到顶部来解决它。 然后结果没问题。 只有SQL结果输出到CSV文件。

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

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

</body></html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM