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.
zip_read()is a PHP function that reads the next entry from an opened ZIP archive and returns detailed information about that entry.
Syntax
zip_read(resource $zip)The $zip parameter is a ZIP file resource returned by zip_open().
Usage Steps
Open the ZIP file
$zip = zip_open('path/to/zipfile.zip');Check if the ZIP file opened successfully
if ($zip) {
// ZIP file opened successfully, continue processing
} else {
// ZIP file failed to open, handle error
}Loop through the entries
while ($zip_entry = zip_read($zip)) {
// Process the current entry
}Close the ZIP file
zip_close($zip);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
$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
";
}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.
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.
