I am trying to dynamically create a downloadable csv file from within WordPress. The data to be included is correct, and the file is created for download successfully. However, the created csv file includes the template HTML output.
How can the data be output, without the HTML from the template?
Here is the function. The arrays are correctly populated with a sql query, but the results are identical to this.
function exportAsCSV ( ) {
$csv = '';
$header_array = array('Header 1', 'Header 2', 'Header 3');
$data_array = array(
array('Row 1 A', 'Row 1 B', 'Row 1 C'),
array('Row 2 A', 'Row 2 B', 'Row 2 C'),
);
$csv .= implode(', ', $header_array);
$csv .= '\n';
foreach($data_array as $row){
$csv .= implode(', ', $row);
$csv .= '\n';
}
$now = gmdate('D, d M Y H:i:s') . ' GMT';
header('Content-Type: text/csv');
header('Expires: ' . $now);
header('Content-Disposition: attachment; filename="data.csv"');
header('Pragma: no-cache');
echo $csv;
exit();
}
The function is called as so:
if(isset($_GET['export_data'])){
ob_end_clean();
exportAsCSV();
}