Reputation: 65
I have a php file which creates a CSV file... however. The contents of the CSV file also include the entire html page as well.
Here's the result:
Number, Access Code, Date
1, 1BIs1B1165n8xba, 29/01/2016
2, 1BIPa%1166vwG&M, 29/01/2016
3, 1BIKES11677GhK0, 29/01/2016
4, 1BIX$T11682w&&@, 29/01/2016
5, 1BIq2N1169npOn5, 29/01/2016
<!DOCTYPE html>
<html dir="ltr" lang="en" xml:lang="en">
<head>
...
...
...
</html>
Here's the code.
ob_clean();
$filename="export.csv";
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private', false);
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=' . $filename);
if(isset($associated_array['0'])) {
$fp = fopen('php://output', 'w');
fputcsv($fp, array_keys($associated_array['0']));
foreach($associated_array AS $values){
fputcsv($fp, $values);
}
fclose($fp);
}
ob_flush();
I've closed the file and I've flushed the buffer so where have I gone wrong please?
Cheers
Dave
Upvotes: 0
Views: 400
Reputation: 8865
If you want to send the csv file to the client then you should exit your script after delivering data.
...
ob_flush();
exit();
If you don't exit()
or die()
any output of your script will be added to the csv file at client side.
Upvotes: 1