28: Read and Write ZIP Archives in Memory
Overview
Section titled “Overview”Build a tiny archive from generated text and read it back without creating a ZIP file on disk.
Prerequisites
Section titled “Prerequisites”- PHP 8.6 CLI. Confirm the version with
php --version. - The
zipextension. - Review the previous chapter if you’re following the series in order.
Allow about 10 minutes for the walkthrough and exercise.
What You’ll Build
Section titled “What You’ll Build”A runnable zip-in-memory.php example.
Step 1: Run the example (~5 min)
Section titled “Step 1: Run the example (~5 min)”Run the following from the root of the Code with PHP repository.
php code/php-8-6/28-zip-in-memory/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();}Expected Result
Section titled “Expected Result”Pack light.Why It Works
Section titled “Why It Works”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.
Exercise
Section titled “Exercise”Add summary.txt and verify that you can read its text after reopening the ZIP bytes.
Wrap-up
Section titled “Wrap-up”Continue with Compiler Optimizations for array_map().