I need a little help here. I intended to create 2 csv files in PHP and have the browser download them. This will happen when users click a button. However, I discovered that only 1 file download is permitted for each http request. I stumbled upon this stackoverflow
post. The solution creates 3 csv files in-memory and added them into a zip file and download it to the client's browser.
I tried the solution marked as correct, but it didn't work. A zip file was downloaded, but it is empty.
What I have tried:
$headers = array('id', 'name', 'age', 'species');
$records = array(
array('1', 'gise', '4', 'cat'),
array('2', 'hek2mgl', '36', 'human')
);
$zipname = 'file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
for ($i = 0; $i < 3; $i++) {
$fd = fopen('php://temp/maxmemory:1048576', 'w');
if (false === $fd) {
die('Failed to create temporary file');
}
fputcsv($fd, $headers);
foreach($records as $record) {
fputcsv($fd, $record);
}
rewind($fd);
$zip->addFromString('file-'.$i.'.csv', stream_get_contents($fd) );
fclose($fd);
}
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
unlink($zipname);