Ne-Lexa / php-zip

PhpZip is a php-library for extended work with ZIP-archives.
MIT License
491 stars 60 forks source link

Extract files to stream #88

Open mstimvol opened 2 years ago

mstimvol commented 2 years ago

Description
It would be great to have a function to extract files to a stream instead of a directory. At the moment, I'm calling openFromStream to read my zip archive and then calling extractTo to extract all the files to a temporary directory. Next, I'm using a foreach-loop to iterate through the files and send them back to another stream. So writing / extracting them to the local disk is completely unnecessary since I want to read the zip archive from a stream, use a foreach loop to iterate over all entries and extract each file to a stream.

Example


$zipfile = new \PhpZip\ZipFile();
$zipfile->openFromStream($myRemoteStream);

foreach ($zipfile as $entryName) {
    $stream = openStream();
    // Extract the content of $entryName to the given stream...
    $zipfile->extractTo($stream, $entryName);
    close($stream);
}

$zipfile->close();
odan commented 1 year ago

You can use the getEntryStream method for this.

Example:


// This is optional: Create a ZIP file as stream
$zipStream = fopen('php://temp', 'ab');
fwrite($zipStream, base64_decode('UEsFBgAAAAAAAAAAAAAAAAAAAAAAAA=='));

$zip = new \PhpZip\ZipFile();
$zip->openFromStream($zipStream);

$zip->addFromString('example.txt', 'my content');
$zip->addFromString('sub1/example2.txt', 'my content2');

$listFiles = $zip->getListFiles();
foreach ($listFiles as $entryName) {
    //  Extract the content of $entryName to the given stream
    $stream = $zip->getEntryStream($entryName);

    // Optional: Convert stream to string
    $content = stream_get_contents($stream);

    fclose($stream);
}

$zip->close();