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

lit*_*leK 4 html php mysql csv

我已经看到了这个帖子,但它并没有真正提供解决方案(至少对我有用)......

我有一个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)
Run Code Online (Sandbox Code Playgroud)

有没有人对如何防止这种情况发生任何想法?如果我发布一些代码,请告诉我,我会......

谢谢!

编辑:

在调用导出函数之前调用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>            
Run Code Online (Sandbox Code Playgroud)

编辑:

调用CSV导出脚本后调用exit()解决了此问题.

Tom*_*igh 8

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

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

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