The PHP documentation offers a simple way to load a ZipArchive
from a file like the following:
$zip = new \ZipArchive();
$zip->open('file.zip');
Using an external file storage which is abstracted away means I don't have local files, but only file content to read files. Is there any way to load a ZipArchive
from the file content?
Something like
$zip->fromString($fileContent);
Only available solutions found here are converting everything into base64 encoding in between which is to memory intensive for larger files and therefore fails.
My Answer:
One way to achieve this is to use PHP's temporary file functionality to create a temporary file from the file content string, and then open the ZipArchive from that temporary file. Here's an example:
php
// Create a temporary file
$tempFile = tmpfile();
fwrite($tempFile, $fileContent);
// Get the file path of the temporary file
$metaData = stream_get_meta_data($tempFile);
$filePath = $metaData['uri'];
// Open the ZipArchive from the temporary file
$zip = new \ZipArchive();
$zip->open($filePath);
// Do your operations with the ZipArchive
// Close and delete the temporary file
fclose($tempFile);
This way, you can open a ZipArchive from the file content string without having to encode it in base64. Just make sure to handle the temporary file properly by closing and deleting it after you're done using it.
Rate this post
3 of 5 based on 3079 votesComments