【问题标题】:how to zip stream csv file php如何压缩流csv文件php
【发布时间】:2013-03-08 03:56:02
【问题描述】:

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

【问题讨论】:

标签: php csv ziparchive zipstream


【解决方案1】:

您应该在导出之前读取一个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);
}

【讨论】:

  • 谢谢,但我想添加 .csv 文件而不在磁盘上创建临时文件
  • 您需要首先 CSV 文件读取数据并将 CSV 文件保存到文件夹并读取 CSV 文件名以放入 ZIP。
  • 我已经更新了答案。您需要将所有字符串数据放入字符串 addString('file.csv', 'your csv strings data read or outputed for CSV');
猜你喜欢
  • 2020-10-21
  • 2017-11-13
  • 2017-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-05
  • 1970-01-01
相关资源
最近更新 更多