如何压缩流csv文件php

时间:2013-03-08 03:56:02

标签: php csv ziparchive zipstream

我使用代码

创建了一个.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文件并下载它。怎么做

1 个答案:

答案 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);
}