如何读取 zip 存档中的单个文件


How to read a single file inside a zip archive

我需要在zip文件内读取单个文件"test.txt"的内容。整个zip文件是一个非常大的文件(2gb(,包含很多文件(10,000,000(,因此提取整个文件对我来说不是一个可行的解决方案。如何读取单个文件?

尝试使用 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;

请注意,如果使用密码保护zip文件,@Rocket-Hazmat fopen解决方案可能会导致无限循环,因为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_contentsfopen

执行此操作
$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/一样传递它末尾的正斜杠。