I'm preparing a CSV file to download.
I know I'm nearly there as the link at the end of this code produces the right result. What I need to do and don't understand why it doesn't work, is create the downloaded file programmtically (using an example from http://php.net/manual/en/function.readfile.php
). If I omit ob_start()
I get "Headers already sent" error, if I include them nothing happens.
What am I doing wrong?
$filename = 'export.csv';
$data = fopen($filename, 'w');
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
fputcsv($data, $row);
}
fclose($data);
if (file_exists($filename)) {
ob_start();
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($filename).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));
readfile($filename);
ob_get_clean();
}
The output file is produced fine, I can see it on the server and it downloads using a link as valid CSV correctly produced. It's purely prompting the download that is not happening.