Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Export MySQL to CSV - Results showing HTML

Tags:

html

php

mysql

csv

I saw a post on this already, but it didn't really provide a solution (that has worked for me at least)...

I have a PHP page that does some basic MySQL queries, the results of which are displayed on the page. I'm using some $_GET and $_SESSION variables throughout this process.

In the same page, I also allow the user to "Export to CSV" (by calling a function). The file returned from the export has the CSV results at the bottom, but also contains the HTML of my page (which calls the function).

Now, at the top of the page I have ob_start() and at the bottom I have ob_flush(), otherwise on page load I will receive some "Cannot modify header..." errors. So, as suggested in the post that I read:

 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)

Does anyone have any ideas on how I can prevent this from happening? Let me know if I should post some of my code and I will...

Thanks!

EDIT:

When calling ob_end_clean() before I call my export function, it gets rid of any html before the CSV. However, I am still getting some HTML closing tags after the CSV results...

 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>            

EDIT:

This issue has been solved by calling exit() after calling the CSV export script.

like image 323
littleK Avatar asked Dec 30 '22 18:12

littleK


1 Answers

You could try calling ob_end_clean() before you output the csv data, and it should throw away any output you have already printed as HTML.

You could call exit() after outputting your csv data in order to stop the rest of you page being printed.

This doesn't seem a particularly good approach, can you not have a separate PHP script to output the csv which doesn't include the headers and footers by default?

like image 187
Tom Haigh Avatar answered Jan 02 '23 10:01

Tom Haigh