Extract folder contents using ZipArchive

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

zip file

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

desired

How can i do this? maybe without recursion?

+4
source share
3 answers

It is possible, but you must read and write the ZipArchive::getStream file 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); } 
+5
source

Look at the docs for extractTo . Example 1

0
source

I got similar @quantme errors when using @netcoder solution. I made changes to this solution and it works without 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(); } 
0
source

Source: https://habr.com/ru/post/1380879/


All Articles