I created an .csv export file with code:
header('Content-type: text.csv');
header('Content-Disposition: attachment; filename=filename.csv');
.....
$fp = fopen('php://output','w');
foreach ($rowsCsv as $rowCsv) {
fwrite($fp, $rowCsv);
}
fclose($fp);
It work ok but I want to compress the csv file to zip file and download it. How do it
You should read a CSV file before exported, or you only need put filename.csv
into file:
$file_folder = "folder_you_stored/"; // change folder
$file = "filename.csv"; // your CSV filename from exported done
$zip = new ZipArchive();
$zip_name = "archiver.zip";
$string_data = 'dumped data of CSV';
$zip->addFile($file_folder.$file); // store a file OR below
$zip->addString("your_filename.csv", $string_data); // file store of string data
# download action
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="'.$zip_name.'"');
header('Content-Length: ' . strlen($string_data));
readfile($zip_name);
unlink($zip_name);
PHP.NET reference how to using ZIP archive: http://php.net/manual/en/class.ziparchive.phpž
Put instead of addFile
add as string as example:
$fp = fopen('php://output','w');
foreach ($rowsCsv as $rowCsv) {
$zip->addFromString('example.csv', $rowCsv);
}