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

标签 php mysql html csv

我已经看到一篇关于此的帖子,但它并没有真正提供解决方案(至少对我有用)...

我有一个执行一些基本 MySQL 查询的 PHP 页面,其结果显示在页面上。我在整个过程中使用了一些 $_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?

关于PHP 将 MySQL 导出为 CSV - 结果显示为 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1197352/

相关文章:

java - Android MySQL + PHP + JSON

android - SQLite 错误 - 滥用聚合 : sum()

html - CSS Transition 不适用于 ng-class

javascript - JS : Slideshow inaccurate result

php - 插入但如果重复则忽略,如果存在于另一个表中则设置不同的值

php + mysql_num_rows 问题?

PHP 不会对 undefined variable 发出警告

php - Doctrine2/Symfony 2 @ParamConverter 使用自定义存储库方法删除未映射的参数

mysql - 非常慢的查询曾经非常快。 Explain 在本地备份上显示 rows=1 但在服务器上显示 rows=2287359

javascript - 节内的节