CSV file export without additional HTML data before and after - PHP

What should I do to avoid showing additional web page HTML data in CSV file exported in PHP ? Additional data are added before and after the CSV data. What is the best way to do CSV export in PHP ?
give a positive ratinggive a negative rating
10 Nov 2022 at 01:27 PM

To export CSV file without showing additional source code before or after the data, you have to use a bit more optimized solution. The reason why additional code is showing in the file is, that your CSV export code is located on the same web page as HTML.

There are a couple of options how to avoid having HTML code in CSV export:

1. Use ob_end_clean() before the CSV export code, to clean the ouput buffer.

2. Use exit() after the CSV export code (it will cut-off the part of code if there is some).

3. Place your CSV export code into a separate part of code or separate file and call it using a jQuery Ajax solution

function export_CSV(id) {

url: '?action=export&id='+id,
method: 'GET',
xhrFields: {
responseType: 'blob'
success: function (data) {
var d = new Date();
var a = document.createElement('a');
var url = window.URL.createObjectURL(data);
a.href = url;
a.download = 'CSV_export_'+d.getFullYear()+(d.getMonth()+1)+d.getDate()+d.getHours()+d.getMinutes()+d.getSeconds()+'.csv';


give a positive ratinggive a negative rating
19 Nov 2022 at 11:15 AM
Share on FacebookShare on TwitterShare on LinkedInSend email
2024 AnswerTabsTermsContact us