使用ZipArchive提取文件夹内容

qua*_*tme 4 php ziparchive

我在具有以下结构的站点上有compressed_file.zip:

zip文件

我想从version_1.x文件夹中提取所有内容到我的根文件夹:

期望

我怎样才能做到这一点?没有递归可能吗?

net*_*der 5

这是可能的,但您必须自己使用ZipArchive::getStream以下方式读取和写入文件:

$source = 'version_1.x';
$target = '/path/to/target';

$zip = new ZipArchive;
$zip->open('myzip.zip');
for($i=0; $i<$zip->numFiles; $i++) {
    $name = $zip->getNameIndex($i);

    // Skip files not in $source
    if (strpos($name, "{$source}/") !== 0) continue;

    // Determine output filename (removing the $source prefix)
    $file = $target.'/'.substr($name, strlen($source)+1);

    // Create the directories if necessary
    $dir = dirname($file);
    if (!is_dir($dir)) mkdir($dir, 0777, true);

    // Read from Zip and write to disk
    $fpr = $zip->getStream($name);
    $fpw = fopen($file, 'w');
    while ($data = fread($fpr, 1024)) {
        fwrite($fpw, $data);
    }
    fclose($fpr);
    fclose($fpw);
}
Run Code Online (Sandbox Code Playgroud)


Joh*_*son 0

查看 的文档extractTo。示例 1。