【问题标题】:Download multiple files as a zip-file using php使用 php 将多个文件下载为 zip 文件
【发布时间】:2010-12-17 18:46:43
【问题描述】:

如何使用 php 将多个文件下载为 zip 文件?

【问题讨论】:

标签: php zip


【解决方案1】:

您可以使用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。第三行是可选的,但某些(主要是较旧的)浏览器在某些情况下会出现问题,而没有指定内容大小。

【讨论】:

  • 不应该是$zip = new ZipArchive; 而不是$zip = new ZipFile; 吗?
  • @Matthieu 括号不是必需的。查看示例:php.net/manual/en/ziparchive.open.php
  • 变量 $zipfilename 应该是什么意思?
  • 它不能在 windows 默认的 zip opener 中工作,但是在 win zipper 或 7-zip 中工作。我正在尝试在 zip 文件夹中添加图像,然后以 zip 格式下载
  • 我试过这个,但是当我尝试解压缩压缩文件时,它说档案不可读,档案可能无效,或者它的目录可能被加密。怎么了?
【解决方案2】:

创建一个 zip 文件,然后下载文件,通过设置标题,读取 zip 内容并输出文件。

http://www.php.net/manual/en/function.ziparchive-addfile.php

http://php.net/manual/en/function.header.php

【讨论】:

    【解决方案3】:

    这是一个用 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();
    

    【讨论】:

    • 这个答案有效!区别在于 addFromString,addFile 编码错误。
    【解决方案4】:

    您已准备好使用 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/

    还有 php pear lib 用于此 http://www.php.net/manual/en/class.ziparchive.php

    【讨论】:

      猜你喜欢
      • 2011-06-27
      • 2018-03-29
      • 2019-03-01
      • 2012-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多