tags:

views:

30

answers:

1

I have a zip file. I need a simple way to read the name of the files from the zip and read the contents of one of the files.

Can this be done directly in memory without saving,opening and reading the files ?

+1  A: 

You need to open the archive and then can iterate over the files by index:

$zip = new ZipArchive();
if ($zip->open('archive.zip'))
{
     for($i = 0; $i < $zip->numFiles; $i++)
     {  
          echo 'Filename: ' . $zip->getNameIndex($i) . '<br />';
     }
}
else
{
     echo 'Error reading .zip!';
}

To read the content of a single file you can use ZipArchive::getStream($name).

$zip = new ZipArchive();
$zip->open("archive.zip");
$fstream = $zip->getStream("index.txt");
if(!$fp) exit("failed\n");

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

Another way to directly do it is using the zip:// stream wrapper:

$file = fopen('zip://' . dirname(__FILE__) . '/test.zip#test', 'r');
...
halfdan
And how do I read the contents of one of the files?
For read-only access you'll need http://www.php.net/manual/en/function.ziparchive-getstream.php otherwise you'll have to extract it first
Fanis
Sorry, somehow misunderstood your question - fixed the answer.
halfdan
This is perfect.One more thing. Can I read the zip from a stream if it's provided by a web service without saving the file ?