Backend Development 3 min read

How to Use PHP zip_read() to Read ZIP File Entries

The article explains PHP's zip_read() function, its syntax, how to open a ZIP file, iterate through entries, retrieve entry names and sizes, and notes its limitations, providing a complete code example for reading ZIP file entries.

php中文网 Courses
php中文网 Courses
php中文网 Courses
How to Use PHP zip_read() to Read ZIP File Entries

zip_read() is a PHP function that reads the next entry from an opened ZIP archive and returns detailed information about that entry.

Syntax

<code>zip_read(resource $zip)</code>

The $zip parameter is a ZIP file resource returned by zip_open() .

Usage Steps

Open the ZIP file

<code>$zip = zip_open('path/to/zipfile.zip');</code>

Check if the ZIP file opened successfully

<code>if ($zip) {
    // ZIP file opened successfully, continue processing
} else {
    // ZIP file failed to open, handle error
}</code>

Loop through the entries

<code>while ($zip_entry = zip_read($zip)) {
    // Process the current entry
}</code>

Close the ZIP file

<code>zip_close($zip);</code>

Within the loop, each call to zip_read() returns the next entry. The variable $zip_entry holds the entry's details, which can be accessed using functions such as zip_entry_name() for the entry name and zip_entry_filesize() for its size.

Example: reading all entries and outputting their names and sizes

<code>$zip = zip_open('path/to/zipfile.zip');

if ($zip) {
    while ($zip_entry = zip_read($zip)) {
        $name = zip_entry_name($zip_entry);
        $size = zip_entry_filesize($zip_entry);
        echo "Name: $name, Size: $size bytes\n";
    }
    zip_close($zip);
} else {
    echo "Failed to open ZIP file\n";
}</code>

This code opens the specified ZIP file, iterates over each entry, retrieves the entry name and size, and prints them. Note that zip_read() only reads entry metadata; it does not extract file contents. To extract files, use functions like zip_entry_open() and zip_entry_read() .

In summary, zip_read() is a useful PHP function for reading ZIP file entry information, facilitating further processing of archive contents.

backendfile handlingzipzip_read
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.