将文件放入zip并流式传输到浏览器 - 零物理文件

时间:2012-11-22 11:10:55

标签: php browser zip download

基本上我们当前生成一个csv文件并将其推送到客户端浏览器以进行下载,因此不会涉及或存储任何物理文件,因为这些文件总是会发生变化。 这些在某些地方变得非常大,我需要降低下载到客户端的速度和大小。

我决定使用zip root并使下面的测试脚本工作正常,但是我仍然需要在物理上生成zip文件然后删除它,显然这里有一个速度因素,因为我正在编写和阅读文件,当我只需要将zip文件内容推送到浏览器时。

是否无法使用ziplib创建流?

<?php


//report
$reportFilename = 'report';
$data = '005,"756607       ","WED","L","TEST UITENHAGE CBD F NFD"
        005,"756608       ","MON","L","TEST SUMMERSTRAND NNB   "
        005,"756634       ","WED","L","TEST UITENHAGE PENFORD F"
        005,"756776       ","MON","L","TEST WALKER DRIVE FOOD  "
        005,"756858       ","MON","C","TEST R ADAMI&SONS C C  "
        005,"801002       ","MON","L","TESTMOFFET NNB "
        005,"CP00270      ","WED","L","TEST  WALMER P FNF       "
        ';   //dummy data

// populate fake data...
$reportData = $data.$data.$data.$data.$data.$data.$data.$data.$data.$data.$data; 

//make unique so no clashing occurs
$zipFilename = '_temp_'.microtime().$zipFilename;

//zip data
$zip = new ZipArchive();
$zip->open($zipFilename, ZIPARCHIVE::CREATE);
$zip->addFromString($reportFilename.'.csv' , $reportData);    //add report
$zip->close();

$zipData = file_get_contents($zipFilename);
$zipSize = filesize($zipFilename);
unlink($zipFilename);

header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=\"".$reportFilename.".zip\"");
header('Content-Transfer-Encoding: binary');
header("Content-Type: application/zip");
echo $zipData;

?>

0 个答案:

没有答案