Library contents

PHP ZipArchive

ZipArchive opens a ZIP file and reads an entry by name. getFromName returns the entry contents as a string or false if the lookup fails.

A simple example

ZipArchive

  1. Start with Archive with entry a.txt containing A
  2. Do this Read the member by name
  3. Result A
Selecting the name identifies which member supplies the bytes.

Syntax

PHP syntax
$content = $zip->getFromName($name)
Run this example in PHP

Save the program as lesson.php. Use PHP 8.2 or later.

php lesson.php

Read a named entry with the object API

A caller asks for a named entry through an object interface. Read the requested entry using its name and check how the API distinguishes a successful lookup from a missing value.

From the programdeclare(strict_types=1)
First output line2 entries
lesson.php
<?php
declare(strict_types=1);

$path = tempnam(sys_get_temp_dir(), 'catalog-');
if ($path === false) throw new RuntimeException('Cannot create temporary file');
try {
    $writer = new ZipArchive();
    if ($writer->open($path, ZipArchive::OVERWRITE) !== true) {
        throw new RuntimeException('Cannot create archive');
    }
    $writer->addFromString('items.txt', "north\n");
    $writer->addFromString('empty.txt', '');
    if (!$writer->close()) throw new RuntimeException('Cannot finalize archive');

    $reader = new ZipArchive();
    if ($reader->open($path) !== true) throw new RuntimeException('Cannot read archive');
    try {
        echo $reader->numFiles . " entries\n";
        if ($reader->getFromName('empty.txt') === '') echo "empty entry\n";
        if ($reader->getFromName('absent.txt') === false) echo "missing entry\n";
    } finally {
        $reader->close();
    }
} finally {
    unlink($path);
}
Output
2 entries
empty entry
missing entry

Compare open strictly with true because errors can be integer codes. A zero-byte entry returns an empty string, which is distinct from false. This example requires PHP's zip extension.

PHP documentation for ZipArchive

Advertisements

Inspect a choir archive

A teacher saves the bytes for the word alto in an uncompressed archive member. Open the member by name and read its text. What does the teacher see?

Givenparts/alto.txt · 4 bytes
Worked resultalto

The archive contains one stored member. Its entry metadata and contents can be inspected independently.

Inspect a workshop archive

A tutor saves the bytes for glaze in a second uncompressed archive member. Open the member by name and read its text. What does the teacher see?

Givenstudio/tag.txt · 5 bytes
Worked resultglaze

The archive contains one stored member. Its entry metadata and contents can be inspected independently.