[英]Download multiple files as a zip-file using php
如何使用php將多個文件下載為zip文件?
您可以使用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();
並流式傳輸:
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
第二行強制瀏覽器向用戶顯示一個下載框,並提示名稱filename.zip。 第三行是可選的,但某些(主要是較舊的)瀏覽器在某些情況下會出現問題,而未指定內容大小。
這是在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();
創建一個zip文件,然后通過設置標題下載文件,讀取zip內容並輸出文件。
http://www.php.net/manual/zh/function.ziparchive-addfile.php
您已經准備好使用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://www.php.net/manual/zh/class.ziparchive.php的 php pear lib
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.