Skip to content

28: Read and Write ZIP Archives in Memory

Build a tiny archive from generated text and read it back without creating a ZIP file on disk.

  • PHP 8.6 CLI. Confirm the version with php --version.
  • The zip extension.
  • Review the previous chapter if you’re following the series in order.

Allow about 10 minutes for the walkthrough and exercise.

A runnable zip-in-memory.php example.

Run the following from the root of the Code with PHP repository.

Terminal window
php code/php-8-6/28-zip-in-memory/zip-in-memory.php
zip-in-memory.php
<?php
declare(strict_types=1);
$archive = new ZipArchive();
if ($archive->openString(flags: ZipArchive::CREATE) !== true
|| !$archive->addFromString('notes.txt', "Pack light.\n")) {
throw new RuntimeException('Could not build the ZIP archive');
}
$bytes = $archive->closeString();
if ($bytes === false) {
throw new RuntimeException('Could not finalize the ZIP archive');
}
$reader = new ZipArchive();
if ($reader->openString($bytes, ZipArchive::RDONLY) !== true) {
throw new RuntimeException('Could not reopen the ZIP archive');
}
try {
$notes = $reader->getFromName('notes.txt');
if ($notes === false) {
throw new RuntimeException('Missing notes.txt');
}
echo $notes;
} finally {
$reader->close();
}
Pack light.

openString() opens an in-memory archive, and a successful closeString() returns its bytes. Opening returns true on success or a failure value or error code, so check it with === true when branching. Budget memory for both the archive and any extracted data.

Add summary.txt and verify that you can read its text after reopening the ZIP bytes.

Continue with Compiler Optimizations for array_map().