I'm generating a csv file for download using the following code.
/**@var array $results contains the results of an SQL query**/
$tmpFile = tmpfile(); //Create a temp file to write the csv to
fputcsv($tmpFile, array_keys($results[0])); //Write the column headers
foreach ($results as $result) { //write each row to the file
fputcsv($tmpFile, $result);
}
rewind($tmpFile); //Rewind the stream
$csv = stream_get_contents($tmpFile); //Get the file as text
fclose($tmpFile); //Done with the temp file.
//Set the download headers
header('Content-Description: File Transfer');
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="testDownload.csv"');
//Output the content
echo $csv;
exit(0);
The download appears to start normally, but after a second I get a message in firefox, "[The file] could not be saved, because the source file could not be read." I've tested this with chrome/safari and have gotten similar results. I've also tested with some static content (not from the database) without success.
In the developer console, I can inspect the network request and see that it comes back with status 200 and if I inspect the response, I see the complete file. I can even copy/paste it into a text file and open it in excel.
Additionally, if I comment out the header()
lines, the file contents display in the browser without issue.
The content is only ~2500 rows, no special characters.