2

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

4

1 回答 1

4

您应该在导出之前读取一个 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);
}
于 2013-03-08T04:02:48.773 回答