Current Location: Home> Latest Articles> Combining zip_entry_name() to get each file name in Zip

Combining zip_entry_name() to get each file name in Zip

M66 2025-06-06

When handling Zip compressed packages in PHP, zip_read and zip_entry_name are two very practical functions. Through them, we can easily read the file name of each file in the Zip package and perform subsequent operations. This article will explain in detail how to use these two functions to get the names of all files in the Zip zip package.

1. Introduction to zip_read and zip_entry_name

  • zip_read : is used to open a Zip resource and return a Zip directory entry pointer, which can be used to iterate through each entry in a Zip file.

  • zip_entry_name : Used to get the file name of the current Zip entry.

It should be noted that zip_read and zip_entry_name depend on PHP's Zip extension and are often used with the zip_open function.

2. Sample code

Here is a complete example of how to open a Zip file, iterate through each of it, and output their file names.

 <?php
// Need to be processed Zip File path
$zipFile = 'example.zip';

// Open Zip document
$zip = zip_open($zipFile);

if (is_resource($zip)) {
    // Traversal Zip Each entry in
    while ($zipEntry = zip_read($zip)) {
        // 获取当前条目的document名
        $fileName = zip_entry_name($zipEntry);
        echo "document名: " . $fileName . "\n";
    }
    // closure Zip resource
    zip_close($zip);
} else {
    echo "无法Open Zip document。\n";
}
?>

3. Code description

  1. Open Zip file <br> Use zip_open to open the Zip file and return a resource handle. If the opening fails, the resource is not returned.

  2. Read entries <br> Read each entry with zip_read until there are no more entries.

  3. Get file name <br> Use zip_entry_name to get the file name of the current entry.

  4. Close Resources <br> Use zip_close to release Zip resources to avoid resource leakage.

4. Things to note

  • zip_open can only open local Zip files and cannot directly process remote URLs. If you need to deal with remote Zip, you can download it locally using other methods of PHP.

  • Make sure that the PHP environment has Zip extension enabled and can be viewed via phpinfo() .

  • If you want to read the entry content, you can use zip_entry_open and zip_entry_read in addition to getting the file name.

5. Summary

With zip_open , zip_read and zip_entry_name , we can easily iterate through all files in the Zip zip package and get their file names. This method is suitable for viewing a list of files in a compressed package easily and quickly.