PHP zip导致平面文件夹结构

时间:2015-06-02 19:35:27

标签: php

我正在使用由前员工创建的PHP zip函数。它压缩文件和文件夹,但我对生成的ZIP文件有两个问题:

一个。它不包括主要的'文件夹
湾它不保留父/子文件夹结构

我想要的是将子文件夹放在父文件夹下,如下所示:

Parent1
   +-- Child1a
   +-- Child1b
Parent2
Parent3
   +-- Child3a
      +-- Subchild3a1
      +-- Subchild3a2

但我最终得到的是ZIP文件中的平面文件夹结构:

Parent1
Child1a
Child1b
Parent2
Parent3
Child3a
Subchild3a1
Subchild3a2

如何使用以下代码解决此问题:

<?php

function folderToZip($folder, &$zipFile, $subfolder = null) {
    if ($zipFile == null) {
        return false;
    }

    $folder .= end(str_split($folder)) == "/" ? "" : "/";
    $subfolder .= end(str_split($subfolder)) == "/" ? "" : "/";

    $handle = opendir($folder);

    while ($f = readdir($handle)) {
        if ($f != "." && $f != ".." && $f != "archive") {
                if (is_file($folder . $f)) {
                        if ($subfolder != null)
                        $zipFile->addFile($folder . $f, $subfolder . $f);
                        else
                        $zipFile->addFile($folder . $f);
        } elseif (is_dir($folder . $f)) {
                $zipFile->addEmptyDir($f);
                folderToZip($folder . $f, $zipFile, $f);
            }
        }
    }
}
?>

<?php

$z = new ZipArchive();
$z->open("test.zip", ZIPARCHIVE::CREATE);
folderToZip("c:/path/to/look/for/files/to/compress/", $z);

echo "<br />Done";

$z->close();

$ex_file = "./archive/back-" . date('Ymd_Hi', time()) . ".zip";

rename("test.zip", $ex_file);

?>



编辑:以下是最终适合我的剧本:

<?php

function folderToZip($folder, $zipFile, $subfolder = null) {
    if ($zipFile == null) {
        return false;
    }

    $folder .= end(str_split($folder)) == "/" ? "" : "/";
    $subfolder .= end(str_split($subfolder)) == "/" || $subfolder == NULL ? "" : "/";

    $handle = opendir($folder);

    while ($f = readdir($handle)) {
      if ($f != "." && $f != ".." && $f != "archive") {
                if (is_file($folder . $f)) {
                        $zipFile->addFile($folder . $f, $subfolder . $f);
        } elseif (is_dir($folder . $f)) {
                $zipFile->addEmptyDir($subfolder . $f);
                folderToZip($folder . $f, $zipFile, $subfolder . $f);
            }
        }
    }
}
?>

<?php

$z = new ZipArchive();
$z->open("test.zip", ZIPARCHIVE::CREATE);
folderToZip("c:/path/to/look/for/files/to/compress/", $z);

echo "<br />Done";

$z->close();

$ex_file = "./archive/back-" . date('Ymd_Hi', time()) . ".zip";

rename("test.zip", $ex_file);

?>

1 个答案:

答案 0 :(得分:0)

此代码似乎不正确:

} elseif (is_dir($folder . $f)) {
   $zipFile->addEmptyDir($f);
   folderToZip($folder . $f, $zipFile, $f);
}

我认为应该是:

} elseif (is_dir($folder . $f)) {
   $zipFile->addEmptyDir($subfolder . $f);
   folderToZip($folder . $f, $zipFile, $subfolder . $f);
}

在不引用$子文件夹并将其传递回递归函数的情况下,您总是引用&#39; /&#39;或者zip文件的根目录。