我需要读取zip文件中的单个文件"test.txt"的内容。整个zip文件是一个非常大的文件(2gb),包含了很多文件(10,000,000),因此无法将整个zip文件解压缩为可行的解决方案。那么我该如何读取单个文件?
尝试使用zip://
包装器:
$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;
phar://
包装器似乎支持此操作。可以使用 file_get_contents('phar://yourfile.tar.gz/path/to/file.txt');
进行访问。参见:https://dev59.com/X2445IYBdhLWcg3wZJiw#4878849 - gen_Ericfile_get_contents('zip://https://example.com/test.zip#test.txt');
会起作用吗?否则,您可能需要先将文件下载到内存(或临时文件夹)中。 - gen_Ericfopen
解决方案可能会导致无限循环,如果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;
不过,有一个解决办法:警告:file_get_contents(zip:// file.zip#file.txt):无法打开流:操作失败
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/
一样通过在末尾添加斜杠传递它。