【发布时间】:2012-05-12 07:16:19
【问题描述】:
我需要读取 zip 文件中的单个文件“test.txt”的内容。整个 zip 文件是一个非常大的文件(2gb)并且包含很多文件(10,000,000),因此提取整个文件对我来说不是一个可行的解决方案。如何读取单个文件?
【问题讨论】:
-
这个问题其实并不傻。我在谷歌搜索“从 zip php 中提取一个文件”时发现自己在这里。奇怪的是它的票数被否决了。
我需要读取 zip 文件中的单个文件“test.txt”的内容。整个 zip 文件是一个非常大的文件(2gb)并且包含很多文件(10,000,000),因此提取整个文件对我来说不是一个可行的解决方案。如何读取单个文件?
【问题讨论】:
尝试使用zip:// wrapper:
$handle = fopen('zip://test.zip#test.txt', 'r');
$result = '';
while (!feof($handle)) {
$result .= fread($handle, 8192);
}
fclose($handle);
echo $result;
你也可以使用file_get_contents:
$result = file_get_contents('zip://test.zip#test.txt');
echo $result;
【讨论】:
is_file 来检查.zip 是否存在。至于zip里面的文件,我不确定。
phar:// wrapper 似乎支持这一点。 file_get_contents('phar://yourfile.tar.gz/path/to/file.txt'); 见:stackoverflow.com/a/4878849
请注意@Rocket-Hazmat fopen 解决方案如果使用密码保护 zip 文件可能会导致无限循环,因为 fopen 将失败并且 feof 无法返回 true。
您可能希望将其更改为
$handle = fopen('zip://file.zip#file.txt', 'r');
$result = '';
if ($handle) {
while (!feof($handle)) {
$result .= fread($handle, 8192);
}
fclose($handle);
}
echo $result;
这解决了无限循环问题,但如果您的 zip 文件受密码保护,那么您可能会看到类似
警告:file_get_contents(zip://file.zip#file.txt):打开失败 流:操作失败
有办法解决
从 PHP 7.2 开始,添加了对加密存档的支持。
所以你可以对 file_get_contents 和 fopen
$options = [
'zip' => [
'password' => '1234'
]
];
$context = stream_context_create($options);
echo file_get_contents('zip://file.zip#file.txt', false, $context);
一个更好的解决方案是使用 ZipArchive
$zip = new ZipArchive;
if ($zip->open('file.zip') !== TRUE) {
exit('failed');
}
if ($zip->locateName('file.txt') !== false) {
echo 'File exists';
} else {
echo 'File does not exist';
}
这会起作用(无需知道密码)
注意:要使用
locateName方法定位文件夹,您需要像folder/一样使用 末尾的正斜杠。
【讨论】: