Home > Back-end >  PHP ZipArchive list only one level of files/folders
PHP ZipArchive list only one level of files/folders

Time:01-12

I have wp.zip and would like to list only one level of files/folders. My current code:

$zip = new \ZipArchive();
$zip->open('wp.zip'), \ZipArchive::RDONLY);

for ($i = 0; $i < $zip->numFiles; $i  ) {
 $stat = $zip->statIndex($i);
 echo $stat['name'] . ' ';
}

This code spits out entire list of files recursively.

I need only first level, like this:

wp-admin/ 
wp-content/ 
index.php 
config.php 
<...>

What's the best approach to achieve my goal?

CodePudding user response:

Yes, you can only parse the name and get the level of the file accordingly.

<?php

$zip = new \ZipArchive();
$zip->open('wp.zip');

function getEntryList($zip, $level = 1){
    $res = [];
    for($i = 0; $i < $zip->numFiles;   $i){
        $name = explode("/", trim($zip->statIndex($i)['name'],"/"));
        if(count($name) == $level   1){
            $res[] = end($name);
        }
    }
    return $res;
}

print_r(getEntryList($zip));
  • Related