在 PHP 中是不是可以在不先提取其内容的情况下检查 Zip 文件的内容?

Posted

技术标签:

【中文标题】在 PHP 中是不是可以在不先提取其内容的情况下检查 Zip 文件的内容?【英文标题】:In PHP is it possible to inspect content of a Zip file without extracting its content first?在 PHP 中是否可以在不先提取其内容的情况下检查 Zip 文件的内容? 【发布时间】:2012-03-22 06:34:24 【问题描述】:

我在 php 中看到了 ZipArchive 类,它可以让您读取 zip 文件。但我想知道是否有一种方法可以在不先提取文件的情况下迭代其内容

【问题讨论】:

PHP library that can list contents of zip / rar files的可能重复 【参考方案1】:

在http://www.php.net/ziparchive 的评论中发现:

以下代码可用于获取所有文件名的列表 一个压缩文件。

<?php
$za = new ZipArchive(); 

$za->open('theZip.zip'); 

for( $i = 0; $i < $za->numFiles; $i++ ) 
    $stat = $za->statIndex( $i ); 
    print_r( basename( $stat['name'] ) . PHP_EOL ); 

?>

【讨论】:

感谢您的回答。在查看 ZipArchive 文档时,我一定错过了 numFiles 字段。 ZipArchive 对象的界面很奇怪。 @flu:只是我现在的想法。看起来比没有类的普通旧 PHP 还要糟糕。 $za 在我的情况下只包含 true ... oO【参考方案2】:

http://www.php.net/manual/en/function.zip-entry-read.php

<?php
$zip = zip_open("test.zip");

if (is_resource($zip))
  
  while ($zip_entry = zip_read($zip))
    
    echo "<p>";
    echo "Name: " . zip_entry_name($zip_entry) . "<br />";

    if (zip_entry_open($zip, $zip_entry))
      
      echo "File Contents:<br/>";
      $contents = zip_entry_read($zip_entry);
      echo "$contents<br />";
      zip_entry_close($zip_entry);
      
    echo "</p>";
  

zip_close($zip);

?>

【讨论】:

zip_entry_read 默认只从文件中读取 1024 个字节。所以 contents 不是文件的全部内容,而只是前 1024 个字节。 警告:此功能已被弃用【参考方案3】:

我这样解决了这个问题。

$zip = new \ZipArchive();

$zip->open(storage_path('app/'.$request->vrfile));

$name = '';

//looped through the zip files and got each index name of the files
//since I only wanted the first name which is the folder name I break the loop 
//after updating the variable $name with the index name and that's it

    for( $i = 0; $i < $zip->numFiles; $i++ )
        $filename = $zip->getNameIndex($i);
        var_dump($filename);
        $name =     $filename;
        if ($i == 1)
            break;
        
    

    var_dump($name);

【讨论】:

为什么不使用$zip-&gt;getNameIndex(0); 而不使用任何循环和中断等? 更重要的是,目前这将获得 second 条目...【参考方案4】:

重复的问题。发帖前先搜索。 PHP library that can list contents of zip / rar files

    <?php

 $rar_file = rar_open('example.rar') or die("Can't open Rar archive");

 $entries = rar_list($rar_file);

 foreach ($entries as $entry) 
     echo 'Filename: ' . $entry->getName() . "\n";
     echo 'Packed size: ' . $entry->getPackedSize() . "\n";
     echo 'Unpacked size: ' . $entry->getUnpackedSize() . "\n";

     $entry->extract('/dir/extract/to/');
 

 rar_close($rar_file);

 ?>

【讨论】:

大声笑,所以你骂一个重复的问题,然后用答案来补贴行为。不错:) 投票关闭重复的问题而不是重复的答案 - 你应该在讲道之前阅读圣经。

以上是关于在 PHP 中是不是可以在不先提取其内容的情况下检查 Zip 文件的内容?的主要内容,如果未能解决你的问题,请参考以下文章

是否可以在不先列出列表的情况下将 Series 附加到 DataFrame 行?

在不先显示 UIView 的情况下将 UIView 转换为 UIImage?

是否可以在不先阅读的情况下更改rails中的记录

如何在不先保存的情况下在 Android 中发送 zip 文件?

我可以在不先选择数据库的情况下使用 Laravel Schema::create Database() 吗?

如何在不先加载到 RAM 的情况下将文件加载到 blob 中?