2012-03-22 102 views
20

我已经看到了PHP中的ZipArchive类,它可以让你阅读zip文件。但我想知道是否有一种方法来迭代虽然它的内容没有提取文件第一个在PHP中,可以先检查Zip文件的内容而不先提取其内容?

+0

可能重复[PHP库,可以列出ZIP/RAR文件的内容(http://stackoverflow.com/questions/1524186/php-library-that -can-list-contents-of-zip-rar-files) – 2012-03-22 06:42:44

回答

39

由于发现的评论​​:

下面的代码可以用来获得 一个zip文件,所有文件名的列表。

<?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); 
} 
?> 
+0

感谢您的回答。在查看ZipArchive文档时,我一定错过了numFiles字段。 – Roman 2012-03-22 08:13:32

+4

ZipArchive对象的接口很奇怪。 – flu 2013-09-03 12:44:35

+0

@flu:只是我现在的想法。看起来比没有类的Plain Old PHP还要糟糕。 – 2015-03-11 08:46:36

-3

重复的问题。发帖前搜索。 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); 

?> 
+9

大声笑,所以你骂一个重复的问题,然后补贴行为与答案。尼斯:) – rdlowrey 2012-03-22 06:42:02

+9

投票关闭重复的问题,而不是重复的答案 - 你应该在讲道之前阅读圣经。 – Repox 2012-03-22 06:51:34

14

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

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

if ($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); 
} 
?>