在内存中下载并解压缩zip存档 [英] In memory download and extract zip archive
问题描述
我想下载一个zip归档文件,并使用PHP将其解压缩到内存中.
I would like to download a zip archive and unzip it in memory using PHP.
这就是我今天所拥有的(对我来说这是太多的文件处理:)):
This is what I have today (and it's just too much file-handling 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...
推荐答案
警告:这无法在内存中完成-ZipArchive
无法与内存映射文件"一起使用.
Warning: This cannot be done in memory — ZipArchive
cannot work with "memory mapped files".
您可以使用 file_get_contents
文档 ,因为它支持
You can obtain the data of a file inside a zip-file into a variable (memory) with file_get_contents
Docs as it supports the zip://
Stream wrapper Docs:
$zipFile = './data/zip.kmz'; # path of zip-file
$fileInZip = 'test.txt'; # name the file to obtain
# read the file's data:
$path = sprintf('zip://%s#%s', $zipFile, $fileInZip);
$fileData = file_get_contents($path);
您只能使用zip://
或通过ZipArchive访问本地文件.为此,您可以先将内容复制到一个临时文件中并使用它:
You can only access local files with zip://
or via ZipArchive. For that you can first copy the contents to a temporary file and work with it:
$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);
这篇关于在内存中下载并解压缩zip存档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!