Current Location: Home> Latest Articles> Complete example of zip_open() + zip_read() + zip_entry_read()

Complete example of zip_open() + zip_read() + zip_entry_read()

M66 2025-06-06

In PHP, the functions of ZIP files are usually handled using zip_open() , zip_read() and zip_entry_read() . They allow us to open a ZIP file, iterate through the file entries in it, and read the file contents. This article will use a complete example to explain how to use these three functions to read a ZIP file.


1. Function introduction

  • zip_open($filename)
    Open a ZIP file and return a resource handle.

  • zip_read($zip)
    Read the next entry in the ZIP file and return a ZIP entry resource.

  • zip_entry_read($entry, $length)
    Read the contents in the ZIP entry and read the maximum number of specified bytes.

  • zip_entry_name($entry)
    Gets the file name of the current ZIP entry.

  • zip_close($zip)
    Close the ZIP file resource.


2. Complete sample code

The following example demonstrates how to open a ZIP file, traverse all files inside, and output the content to the browser:

 <?php
// ZIPFile path(Please replace it with the actual path)
$zipFile = 'http://m66.net/path/to/your.zip';

// OpenZIPdocument
$zip = zip_open($zipFile);

if (!$zip || is_numeric($zip)) {
    die("无法OpenZIPdocument");
}

echo "<h2>ZIPdocument内容列表:</h2>";

while ($entry = zip_read($zip)) {
    // 获取当前document名
    $fileName = zip_entry_name($entry);
    echo "<h3>document名: $fileName</h3>";

    // OpenZIPentry
    if (zip_entry_open($zip, $entry)) {
        $fileSize = zip_entry_filesize($entry);
        $content = '';

        // 按块读取document内容(The most each time1024byte)
        while ($data = zip_entry_read($entry, 1024)) {
            $content .= $data;
        }

        // Close the currentZIPentry
        zip_entry_close($entry);

        // 输出document内容(Here is a simple output in text,Note that binary data may be included)
        echo "<pre>" . htmlspecialchars($content) . "</pre>";
    } else {
        echo "无法Opendocumententry: $fileName<br>";
    }
}

// closureZIPdocument
zip_close($zip);
?>

3. Things to note

  1. zip_open() supports local file paths, and remote URLs support allow_url_fopen settings that depend on PHP. If remote opening fails, it is recommended to download the ZIP file locally before operating.

  2. When reading the contents of binary files, direct output may cause garbled code or page exceptions. It is recommended to process data as required.