【问题标题】:How to read a single file inside a zip archive如何读取 zip 存档中的单个文件
【发布时间】:2012-05-12 07:16:19
【问题描述】:

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

【问题讨论】:

  • 这个问题其实并不傻。我在谷歌搜索“从 zip php 中提取一个文件”时发现自己在这里。奇怪的是它的票数被否决了。

标签: php zip gzip zlib


【解决方案1】:

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

【讨论】:

  • 如何判断文件是否存在? if(!@$test = file_get_contents(... ?
  • @user1243068:我不确定。那应该行得通。您可以使用is_file 来检查.zip 是否存在。至于zip里面的文件,我不确定。
  • 它也适用于文件,例如 $content=file('zip://test.zip#test.txt');
  • @Sami:phar:// wrapper 似乎支持这一点。 file_get_contents('phar://yourfile.tar.gz/path/to/file.txt'); 见:stackoverflow.com/a/4878849
  • @RocketHazmat - 知道如何使用远程 https 文件执行此操作吗?
【解决方案2】:

请注意@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/ 一样使用 末尾的正斜杠。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-15
    • 1970-01-01
    相关资源
    最近更新 更多