我使用代码
创建了一个.csv导出文件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);
它工作正常,但我想将csv文件压缩为zip文件并下载它。怎么做
答案 0 :(得分:3)
您应该在导出之前阅读CSV文件,或者只需将filename.csv
放入文件中:
$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参考如何使用ZIP存档:http://php.net/manual/en/class.ziparchive。phpž
代替addFile
添加为字符串作为示例:
$fp = fopen('php://output','w');
foreach ($rowsCsv as $rowCsv) {
$zip->addFromString('example.csv', $rowCsv);
}