Hi,
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) {
$.ajax({
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';
document.body.append(a);
a.click();
a.remove();
window.URL.revokeObjectURL(url);
}
});
}