Techie
Techie

Reputation: 45124

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 ?

Upvotes: 1

Views: 3636

Answers (2)

iiro
iiro

Reputation: 3118

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
)

Upvotes: 2

Techie
Techie

Reputation: 45124

$zip = zip_open('zipfile.zip'); 

if ($zip) {
    while ($zip_entry = zip_read($zip)) {
        echo "Name:               " . zip_entry_name($zip_entry) . "\n";
        echo "Actual Filesize:    " . zip_entry_filesize($zip_entry) . "\n";
        echo "Compressed Size:    " . zip_entry_compressedsize($zip_entry) . "\n";
        echo "Compression Method: " . zip_entry_compressionmethod($zip_entry) . "\n";

        if (zip_entry_open($zip, $zip_entry, "r")) {
            echo "File Contents:\n";
            $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
            echo "$buf\n";

            zip_entry_close($zip_entry);
        }
        echo "\n";

    }

    zip_close($zip);

}

Extracted from http://www.php.net/manual/en/zip.examples.php

Note

But this does not support a way to figure out whether it's a folder or a file.

Upvotes: 0

Related Questions