我想下载一个zip归档文件,并使用PHP将其解压缩到内存中。

这就是我今天所拥有的(对我来说,这是太多的文件处理:)):

// 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无法与“内存映射文件”一起使用。

您可以使用 file_get_contents 将zip文件中的文件数据获取到变量(内存)中,因为它支持 zip:// Stream wrapper :

$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访问本地文件。为此,您可以先将内容复制到一个临时文件中并使用它:
$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);

关于php - 在内存中下载并解压缩zip存档,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7391969/

10-09 21:01
查看更多