Divesh Dobal
Divesh Dobal

Reputation: 31

Extract content of zip string

I have a string of a zip file that contains one single text file.

How could I get the contents of the text file without having to deal with files on the disk?

I tried below solution, but it does not work for me.

$written = file_put_contents('php://memory', $zip_string);
$zip = new ZipArchive;
if ($zip->open($written) === TRUE) {
    $zip->extractTo('destination');
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}

Upvotes: 1

Views: 947

Answers (3)

Fabien Salles
Fabien Salles

Reputation: 1181

This works for me :

public function extractContent(string $zipContent): string
{
     // create a temporary file in order to put the zip content and open it
     $tmpZipFile = tmpfile();
     fwrite($tmpZipFile, $zipContent);
     $zip = new ZipArchive();
     $zip->open(stream_get_meta_data($tmpZipFile)['uri']);

     // retrieve the first file of the zip archive
     $content = $zip->getFromIndex(0);

     // close the archive and delete the file
     $zip->close();
     fclose($tmpZipFile);

     return $content;
}

Upvotes: 1

Divesh Dobal
Divesh Dobal

Reputation: 31

My problem was solved by change the way of data compression. Instance of sending data in a compressed file just add a compression header Content-Encoding on response from server. This header compress your data. https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding

Upvotes: 0

timiTao
timiTao

Reputation: 1413

Please, use function extractTo

Instalation

To use this, you must compile PHP with zip support by using the --enable-zip configure option.

Upvotes: 0

Related Questions