In memory, load and extract a zip archive

I would like to download a zip archive and unzip it in memory using PHP.

This is what I have today (and this is too much file processing for me :)):

// download the data file from the real page
copy("http://www.curriculummagic.com/AdvancedBalloons.kmz", "./data/zip.kmz");

// unzip it
$zip = new ZipArchive;
$res = $zip->open('./data/zip.kmz');
if ($res === TRUE) {
    $zip->extractTo('./data');
    $zip->close();
}

// use the unzipped files...
+5
source share
4 answers

Warning . It is impossible to do in memory. ZipArchivecannot work with "memory mapped files".

You can get the file data inside a zip file into a variable (memory) using file_get_contents Docs , as it supports Docszip:// stream wrapper :

$zipFile = './data/zip.kmz';     # path of zip-file
$fileInZip = 'test.txt';         # name the file to obtain

# read the file data:
$path = sprintf('zip://%s#%s', $zipFile, $fileInZip);
$fileData = file_get_contents($path);

zip:// ZipArchive. :

$zip = 'http://www.curriculummagic.com/AdvancedBalloons.kmz';
$file = 'doc.kml';

$ext = pathinfo($zip, PATHINFO_EXTENSION);
$temp = tempnam(sys_get_temp_dir(), $ext);
copy($zip, $temp);
$data = file_get_contents("zip://$temp#$file");
unlink($temp);
+8

:

$zipFile = "test.zip";
$fileInsideZip = "somefile.txt";
$content = file_get_contents("zip://$zipFile#$fileInsideZip");
+2

You can get the stream to a file inside zip and extract it into a variable:

$fp = $zip->getStream('test.txt');
if(!$fp) exit("failed\n");

while (!feof($fp)) {
    $contents .= fread($fp, 1024);
}

fclose($fp);
0
source

If you can use system calls, the easiest way should look like this (bzip2 case). You just use stdout.

$out=shell_exec('bzip2 -dkc '.$zip);
0
source

All Articles