Current Location: Home> Latest Articles> PHP zip_entry_read() Function Explained: How to Read ZIP File Contents

PHP zip_entry_read() Function Explained: How to Read ZIP File Contents

gitbox 2025-06-15

1. Introduction

The PHP zip_entry_read() function is used to read data from files inside a ZIP archive. This function depends on the zip_entry object, which must be opened first using the zip_entry_open() function. The zip_entry_read() function reads data from the ZIP file using an internal pointer, and when it reaches the end of the file, it returns an empty string, indicating that the file has been completely read.

2. Function Prototype

zip_entry_read Function Prototype


string zip_entry_read(resource $zip_entry, int $length)
        

zip_entry_open Function Prototype


bool zip_entry_open(resource $zip, resource $zip_entry [, string $mode = "rb"])
        

3. Parameter Explanation

zip_entry_read Function Parameters

This function has two parameters:

  • zip_entry: The zip_entry object to read from.
  • length: The number of bytes to read.

zip_entry_open Function Parameters

This function has three parameters:

  • zip: The zip stream to open.
  • zip_entry: The zip_entry object to open.
  • mode: The mode to open the zip file. The default is "rb", meaning read-only mode.

4. Return Value Explanation

The return value of the zip_entry_read() function is a string that contains the data read from the zip_entry file. If the end of the file is reached, it returns an empty string.

The zip_entry_open() function returns a boolean value, indicating whether the zip_entry object was successfully opened. It returns true if successful, and false otherwise.

5. Sample Code

Here is a sample showing how to use the zip_entry_read() function to read files from a ZIP archive:


<?php
// Open the zip file
$zip = zip_open("test.zip");
if ($zip) {
    while ($zip_entry = zip_read($zip)) {
        $entry_name = zip_entry_name($zip_entry);
        if (substr($entry_name, -1) != '/') {
            if (zip_entry_open($zip, $zip_entry, "r")) {
                echo "Contents of $entry_name:";
                while ($data = zip_entry_read($zip_entry, 1024)) {
                    echo $data;
                }
                zip_entry_close($zip_entry);
            }
        }
    }
    zip_close($zip);
}
?>
        

The code above iterates through all the files in the "test.zip" file and reads their contents.

6. Notes

When reading large files, it's recommended to call the zip_entry_read() function multiple times, reading a portion of the data each time and checking if the end of the file has been reached. This helps reduce memory usage and improve performance.

Additionally, make sure to call the zip_entry_open() function before using zip_entry_read(), as attempting to read without opening the zip_entry object will result in an error.