使用 php 将多个文件下载为 zip 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1754352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Download multiple files as a zip-file using php
提问by cletus
How can I download multiple files as a zip-file using php?
如何使用 php 将多个文件下载为 zip 文件?
回答by cletus
You can use the ZipArchiveclass to create a ZIP file and stream it to the client. Something like:
您可以使用ZipArchive该类创建 ZIP 文件并将其流式传输到客户端。就像是:
$files = array('readme.txt', 'test.html', 'image.gif');
$zipname = 'file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($files as $file) {
$zip->addFile($file);
}
$zip->close();
and to stream it:
并流式传输它:
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
The second line forces the browser to present a download box to the user and prompts the name filename.zip. The third line is optional but certain (mainly older) browsers have issues in certain cases without the content size being specified.
第二行强制浏览器向用户呈现一个下载框并提示名称 filename.zip。第三行是可选的,但某些(主要是较旧的)浏览器在某些情况下会出现问题,而没有指定内容大小。
回答by Sun Love
This is a working example of making ZIPs in PHP:
这是在 PHP 中制作 ZIP 的工作示例:
$zip = new ZipArchive();
$zip_name = time().".zip"; // Zip name
$zip->open($zip_name, ZipArchive::CREATE);
foreach ($files as $file) {
echo $path = "uploadpdf/".$file;
if(file_exists($path)){
$zip->addFromString(basename($path), file_get_contents($path));
}
else{
echo"file does not exist";
}
}
$zip->close();
回答by dev.meghraj
You are ready to do with php zip lib, and can use zend zip lib too,
您已准备好使用 php zip lib,也可以使用 zend zip lib,
<?PHP
// create object
$zip = new ZipArchive();
// open archive
if ($zip->open('app-0.09.zip') !== TRUE) {
die ("Could not open archive");
}
// get number of files in archive
$numFiles = $zip->numFiles;
// iterate over file list
// print details of each file
for ($x=0; $x<$numFiles; $x++) {
$file = $zip->statIndex($x);
printf("%s (%d bytes)", $file['name'], $file['size']);
print "
";
}
// close archive
$zip->close();
?>
http://devzone.zend.com/985/dynamically-creating-compressed-zip-archives-with-php/
http://devzone.zend.com/985/dynamically-creating-compressed-zip-archives-with-php/
and there is also php pear lib for this http://www.php.net/manual/en/class.ziparchive.php
还有这个http://www.php.net/manual/en/class.ziparchive.php 的php pear lib
回答by Priyank Bolia
Create a zip file, then download the file, by setting the header, read the zip contents and output the file.
创建一个 zip 文件,然后下载文件,通过设置标题,读取 zip 内容并输出文件。
http://www.php.net/manual/en/function.ziparchive-addfile.php
http://www.php.net/manual/en/function.ziparchive-addfile.php

