【问题标题】:Adding files into zip adds the folders containing the files将文件添加到 zip 中会添加包含文件的文件夹
【发布时间】:2020-04-13 12:48:24
【问题描述】:

所以我有一个目录,它的根目录包含一个 files 文件夹,里面有一个包含 txt 文件的 test 文件夹,然后我有这个 php 代码:


    function displayZip($name)
   $zip = new ZipArchive();
   $filename = "files/$name.zip";

  if ($zip->open($filename, ZipArchive::CREATE)!==TRUE) {
      exit("cannot open <$filename>\n");
  }

  $dir = "files/$name/";
  createZip($zip, $dir);

  $zip->close();
  rmdir("files/$name");
 }

 function createZip($zip,$dir, $name){
  if (is_dir($dir)){

    if ($dh = opendir($dir)){
       while (($file = readdir($dh)) !== false){

         // If file
         if (is_file($dir.$file)) {
            if($file != '' && $file != '.' && $file != '..'){
               $zip->addFile($dir.$file);
            }
        }
   }
closedir($dh);
}
}

它为$name变量下的zip命名,然后指定$filename下的完整路径,然后创建zip存档,然后调用createZip函数打开与zip同名的目录,然后在 zip 中添加此目录下的文件,但是当我调用 displayZip(’test’) 然后打开创建的 zip 时,我看到它在其中添加了 files/test/ 文件夹。所以我的问题是:

  1. 它在代码中的什么位置添加这些文件夹,是在addFile 行的$dir.$file 部分吗?
  2. 我该怎么做才能只获取 zip 中的文件?

提前致谢

【问题讨论】:

    标签: php zip


    【解决方案1】:

    默认情况下,ZipArchive 会将文件夹添加到存档中。您可以通过在addFile() 中将“本地名称”指定为第二个参数来删除文件夹。该“本地名称”将是 zip 存档中的结构。详情请见https://www.php.net/manual/en/ziparchive.addfile.php

    rmdir 可能无法正常工作,因为目录不为空。

    【讨论】:

    • 非常感谢,它解决了我的问题!你对 rmdir 也是正确的,我忘记了这个错误......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-02
    • 1970-01-01
    • 2015-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多