Search code examples
phpdirectorydirectory-structurezip

How to get the zip file's directory structure in PHP?


zipfile.zip file's directory structure would be

Folder A -> Folder B -> Folder C -> image1.png, image2.png, image3.png

Below is the code I have tried. But it does not echo anything.

$zip = zip_open('zipfile.zip'); 
while($zip_entry = zip_read($zip)){
    $filename = zip_entry_name($zip_entry);
    echo $filename."<br/>"; 
}

All I want as O/P is

FolderArray => A,B,C

FileArray => image1.png, image2.png, image3.png.

Is it possible to get an O/P as two arrays ? How can I distinguish a file & a folder using PHP zip commands ?

How can I read this directory structure using php ?


Solution

  • I'm not very sure what do you want but here is a one guess. Could you test that the found entry is a folder if it's last char is / ?

    New folder.zip content

    New folder/New folder/New folder/New Text Document (2).txt
    New folder/New folder/New folder/New Text Document.txt
    New folder/New folder/New Text Document.txt
    

    The code

    $zip = zip_open('New folder.zip'); 
    $dirs = $files = array();
    
    if ($zip) {
        while ($zip_entry = zip_read($zip)) {
            $zen = zip_entry_name($zip_entry);
            $is_dir = substr($zen, -1) == DIRECTORY_SEPARATOR;
    
            $zen_splitted = explode(DIRECTORY_SEPARATOR, $zen);
            if ($is_dir) {
    
                $dirs[]  = $zen_splitted[count($zen_splitted)-2];
            } else {
                $files[]  = $zen_splitted[count($zen_splitted)-1];
            }
        }
    
        zip_close($zip);
    
    }
    
    print_r($dirs);
    print_r($files);
    

    The output

    Array
    (
        [0] => New folder
        [1] => New folder
        [2] => New folder
        [3] => New folder (2)
    )
    Array
    (
        [0] => New Text Document (2).txt
        [1] => New Text Document.txt
        [2] => New Text Document.txt
    )