I'm having a problem getting my export to create and download a cvs file. Using the code below, this exports the data, but it prints out in the browser, rather than creating an actual csv file. I call the php from a link on another page with <a href="export.php" target="_blank">Export Details</a>
but all it does is show the data in the browser rather than creating a csv file.
This is my code in the file export.php:
<?php
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="sample.csv"');
$data = array(
'aaa,bbb,ccc,dddd',
'123,456,789',
'"aaa","bbb"'
);
$fp = fopen('php://output', 'w');
foreach ( $data as $line ) {
$val = explode(",", $line);
fputcsv($fp, $val);
}
fclose($fp);
?>
Can anyone see where it's going wrong?
CSV Files are files having comma separated values on each line, maybe enclosed by a string enclosure.
First thing that catches my eye is that you pass single values to fputcsv(). But fputcsv() wants an array of values (fields) as the second argument. So your explode is redundant - have a look at the manual page,
As you are only outputting to STDOUT (the Browser) you can simply echo your lines:
<?php
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="sample.csv"');
$data = array(
'aaa,bbb,ccc,dddd',
'123,456,789',
'"aaa","bbb"'
);
foreach($data AS $line){
echo $line.PHP_EOL;
}
?>
So, after a whole afternoon of fun with this one, I finally got to the bottom of the problem. The issue wasn't with the code, it was the database I am running locally. I'm using Mamp to set up my wordpress db locally and that's where the problem was. The solution is with Output Buffering and the solution can be found here http://hibbard.eu/php-headerlocation-not-working-in-mamp/. Thanks guys for your help ;-)