【问题标题】:Php ZipArchive create zip without all folders [duplicate]Php ZipArchive 创建没有所有文件夹的 zip [重复]
【发布时间】:2016-06-14 01:26:55
【问题描述】:

我在创建 zip 存档文件时遇到问题。

我有一个文件夹 2016_03_01_full,应该可以通过这个路径存档。

C:\OpenServer\domains\project\backup\2016_03_01_full

Zip 存档应与文件夹 2016_03_01_full.zip 同名

C:\OpenServer\domains\stereoshoots\backup\2016_03_01_full.zip

这是我的功能

public function createArchive($source, $destination) {
        $zip = new \ZipArchive();

        if(!$zip->open($destination, \ZipArchive::CREATE))
            return false;

        $source = str_replace('\\', '/', realpath($source));

        if(is_dir($source) === true) {
            $files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($source), \RecursiveIteratorIterator::SELF_FIRST);

            foreach ($files as $file) {
                $file = str_replace('\\', '/', $file);

                if(in_array(substr($file, strrpos($file, '/') + 1), array('.', '..')))
                    continue;

                $file = realpath($file);

                if(is_dir($file) === true)
                    $zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
                elseif(is_file($file) === true)
                    $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
            }
        }
        elseif(is_file($source) === true)
            $zip->addFromString(basename($source), file_get_contents($source));

        return $zip->close();
    }

$this->createArchive($this->getBackupFolderDir().'/', $this->getBackupFolderDir().'.zip');

它确实创建了存档,但它从路径创建了所有文件夹。因此,当我打开 zip 时,我会在其中看到 OpenServer\domains\project\backup\2016_03_01_full 文件夹。有没有没有路径文件夹的存档方法?

谢谢!

【问题讨论】:

  • var_dump($this->getBackupFolderDir()); 给了什么?
  • C:\OpenServer\domains\project\backup\2016_03_01_full

标签: php ziparchive


【解决方案1】:

所创建存档的“目标路径”包含目标文件的绝对(完整)路径。
要省略完整路径 - 仅指定 filename 作为 destination 路径(使用 substrstrrpos 提取文件名函数):

...
$destination = substr($destination, strrpos($destination, DIRECTORY_SEPARATOR) + 1);
if (!$zip->open($destination, \ZipArchive::CREATE)) return false;
...

【讨论】:

  • 它应该如何知道将 zip 保存在哪里?它不适合我。
猜你喜欢
  • 2011-04-28
  • 1970-01-01
  • 2020-02-21
  • 1970-01-01
  • 2013-07-10
  • 1970-01-01
  • 1970-01-01
  • 2018-12-06
  • 2013-04-29
相关资源
最近更新 更多