【问题标题】:PHP extract zip [duplicate]PHP提取zip [重复]
【发布时间】:2013-04-02 18:42:33
【问题描述】:

我有一个 zip 文件,里面有一些文件和文件夹,我想从 zip 文件中提取文件夹“/files”的内容到指定路径(我的应用程序的根路径)。

如果有一个不存在的文件夹,则应该创建它。

例如,如果 zip 中的路径是:“/files/includes/test.class.php”,则应将其提取到

$path . "/includes/test.class.php"

我该怎么做?

我发现在 zip 文件中切换的唯一功能应该是

http://www.php.net/manual/en/ziparchive.getstream.php

但我实际上不知道如何使用此功能做到这一点。

【问题讨论】:

  • 步骤 1) 阅读 documentation 仅供参考 ZipArchive 将保留目录结构,因此您不必担心。
  • 是的,但我不想将 zip 的根目录提取到我的应用程序的根目录。我想从 zip 中提取“/files”到我的根目录。
  • 是的,但要重申最后一点,有人还在...(你猜对了)文档herehere 中提到了这一点——我还清楚地记得以前在 Stackoverflow 上看到过这个问题!

标签: php zip extract


【解决方案1】:

试试这个:

$zip = new ZipArchive;
$archiveName = 'test.zip';
$destination = $path . '/includes/';
$pattern = '#^files/includes/(.)+#';
$patternReplace = '#^files/includes/#';

function makeStructure($entry, $destination, $patternReplace)
{
    $entry = preg_replace($patternReplace, '', $entry);
    $parts = explode(DIRECTORY_SEPARATOR, $entry);
    $dirArray = array_slice($parts, 0, sizeof($parts) - 1);
    $dir = $destination . join(DIRECTORY_SEPARATOR, $dirArray);
    if (!file_exists($dir)) {
        mkdir($dir, 0777, true);
    }
    if ($dir !== $destination) {
        $dir .= DIRECTORY_SEPARATOR;
    }
    $fileExtension = pathinfo($entry, PATHINFO_EXTENSION);
    if (!empty($fileExtension)) {
        $fileName = $dir . pathinfo($entry, PATHINFO_BASENAME);
        return $fileName;
    }
    return null;
}

if ($zip->open($archiveName) === true) {
    for ($i = 0; $i < $zip->numFiles; $i++) {
        $entry = $zip->getNameIndex($i);
        if (preg_match($pattern, $entry)) {
            $file = makeStructure($entry, $destination, $patternReplace);
            if ($file === null) {
                continue;
            }
            copy('zip://' . $archiveName . '#' . $entry, $file);
        }
    }
    $zip->close();
}

【讨论】:

  • 谢谢,但如果我只有这个特定的文件,那就行了,但我想将“/files”的全部内容提取到“/”。
  • 谢谢你,这真的很好用。只是一个小问题。如果 zip 存档中有子文件夹,它们目前不会被复制。有没有办法复制它们,以保持结构?谢谢
  • 如果压缩包中有子文件夹,它们会被创建为一个文件。
  • @Michael 你想复制文件夹吗?还是只是文件?
  • 给定 zip 文件夹“/files”中的所有内容。
【解决方案2】:

我认为您需要 zziplib 扩展才能使其工作

$zip = new ZipArchive;

if ($zip->open('your zip file') === TRUE) {
  //create folder if does not exist
  if (!is_dir('path/to/directory')) {
      mkdir('path/to/directory');
  }

  //then extract the zip
  $zip->extractTo('destination to which zip is to be extracted');
  $zip->close();
  echo 'Zip successfully extracted.';
} else {
  echo 'An error occured while extracting.';
}

阅读此链接了解更多信息http://www.php.net/manual/en/ziparchive.extractto.php

希望这会有所帮助:)

【讨论】:

  • 谢谢,但这不会回答问题。我不想将 zip 的根目录提取到我的应用程序的根目录。我想从 zip 中提取“/files”到我的根目录。
  • 也许这可以帮助你然后stackoverflow.com/questions/10968359/…
猜你喜欢
  • 2018-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-08
  • 1970-01-01
相关资源
最近更新 更多