从ZIP字符串中提取文件 [英] Extract a file from a ZIP string
问题描述
我有一个zip文件的BASE64字符串,其中包含一个XML文件.
I have a BASE64 string of a zip file that contains one single XML file.
关于无需处理磁盘上的文件如何获取XML文件内容的任何想法?
Any ideas on how I could get the contents of the XML file without having to deal with files on the disk?
我非常希望将整个过程保留在内存中,因为XML只有1-5k.
I would like very much to keep the whole process in the memory as the XML only has 1-5k.
不得不编写zip,提取XML然后加载并删除所有内容,这会很烦人.
It would be annoying to have to write the zip, extract the XML and then load it up and delete everything.
推荐答案
经过数小时的研究,我认为在没有临时文件的情况下处理zip是不可能的:
After some hours of research I think it's surprisingly not possible do handle a zip without a temporary file:
- 第一次尝试使用
php://memory
将不起作用,因为它是诸如file_get_contents()
或ZipArchive::open()
之类的函数无法读取的流.注释中是缺少此问题文档的php-bugtracker链接. - 具有
ZipArchive
和::getStream()
的流支持,但是如手册中所述,它仅支持对打开的文件进行读取操作.因此,您不能使用它来快速建立存档. -
zip://
包装器也是只读的:使用fopen创建ZIP文件( )包装器 -
我还尝试了其他类似php wrapper/protocolls的尝试
- The first try with
php://memory
will not work, beacuse it's a stream that cannot be read by functions likefile_get_contents()
orZipArchive::open()
. In the comments is a link to the php-bugtracker for the lack of documentation of this problem. - There is a stream support
ZipArchive
with::getStream()
but as stated in the manual, it only supports reading operation on an opened file. So you cannot build a archive on-the-fly with that. - The
zip://
wrapper is also read-only: Create ZIP file with fopen() wrapper I also did some attempts with the other php wrappers/protocolls like
file_get_contents("zip://data://text/plain;base64,{$base64_string}#test.txt")
$zip->open("php://filter/read=convert.base64-decode/resource={$base64_string}")
$zip->open("php://filter/read=/resource=php://memory")
但是对我来说,它们根本不起作用,即使手册中有类似的例子.因此,您必须吞下药丸并创建一个临时文件.
but for me they don't work at all, even if there are examples like that in the manual. So you have to swallow the pill and create a temporary file.
原始答案:
这只是临时存储的方式.希望您自己管理xml的zip处理和解析.
This is just the way of temporary storing. I hope you manage the zip handling and parsing of xml on your own.
使用php php://memory
( doc )包装.请注意,这仅对小文件有用,因为它显然存储在内存中.否则,请使用php://temp
.
Use the php php://memory
(doc) wrapper. Be aware, that this is only usefull for small files, because its stored in the memory - obviously. Otherwise use php://temp
instead.
<?php
// the decoded content of your zip file
$text = 'base64 _decoded_ zip content';
// this will empty the memory and appen your zip content
$written = file_put_contents('php://memory', $text);
// bytes written to memory
var_dump($written);
// new instance of the ZipArchive
$zip = new ZipArchive;
// success of the archive reading
var_dump(true === $zip->open('php://memory'));
这篇关于从ZIP字符串中提取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!