Master PHP’s zip_read(): Read ZIP Entries Efficiently
This guide explains how to use PHP’s zip_read() function to open a ZIP archive, iterate through its entries, retrieve each entry’s name and size, and properly close the archive, while noting its limitations and related extraction functions.
zip_read()is a PHP function that reads the next entry from an opened ZIP archive and returns its details.
Syntax
zip_read(resource $zip)The $zip parameter is a ZIP file resource returned by zip_open(). zip_read() returns a resource containing entry details or false when no more entries are available.
Usage Steps
Open the ZIP file
$zip = zip_open('path/to/zipfile.zip');Check if the ZIP file opened successfully
if ($zip) {
// continue processing
} else {
// handle error
}Loop through entries
while ($zip_entry = zip_read($zip)) {
// process each entry
}Close the ZIP file
zip_close($zip);Inside the loop, each call to zip_read() returns the next entry, stored in $zip_entry. Use zip_entry_name() to get the entry name, zip_entry_filesize() for its size, etc.
Example: read all entries and output their names and sizes.
$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
";
}
zip_close($zip);
} else {
echo "Failed to open ZIP file
";
}Note that zip_read() only reads entry metadata; it does not extract files. To extract, use functions such as zip_entry_open() and zip_entry_read().
In summary, zip_read() is a useful PHP function for retrieving information about ZIP entries, facilitating further processing.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
