Extract folder content using ZipArchive

怎甘沉沦 提交于 2019-12-06 05:33:00

问题


I have compressed_file.zip on a site with this structure:

I want to extract all content from version_1.x folder to my root folder:

How can I do that? is possible without recursion?


回答1:


It's possible, but you have to read and write the file yourself using 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);
}



回答2:


Look at the docs for extractTo. Example 1.




回答3:


I was getting similar errors to @quantme when using @netcoder's solution. I made a change to that solution and it works without any errors.

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

$zip = new ZipArchive;
if($zip->open('myzip.zip') === TRUE) {
    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
        if($dir != $target) {
            $fpr = $zip->getStream($name);
            $fpw = fopen($file, 'w');
            while ($data = fread($fpr, 1024)) {
                fwrite($fpw, $data);
            }
            fclose($fpr);
            fclose($fpw);
        }
    }
    $zip->close();
}


来源:https://stackoverflow.com/questions/8102379/extract-folder-content-using-ziparchive

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!