在 PHP 中是否可以检查 Zip 文件的内容而不先提取其内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9817525/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In PHP is it possible to inspect content of a Zip file without extracting its content first?
提问by Roman
I have seen the ZipArchive class in PHP which lets you read zip files. But I'm wondering if there is a way to iterate though its content without extracting the file first
我见过 PHP 中的 ZipArchive 类,它可以让您读取 zip 文件。但我想知道是否有一种方法可以在不先提取文件的情况下迭代其内容
回答by deceze
As found as a comment on http://www.php.net/ziparchive:
正如对http://www.php.net/ziparchive的评论所发现的:
The following code can be used to get a list of all the file names in a zip file.
<?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 ); } ?>
以下代码可用于获取 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 ); } ?>
回答by Jerem
http://www.php.net/manual/en/function.zip-entry-read.php
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);
}
?>
回答by Marvin Collins
I solved the problem like this.
我这样解决了这个问题。
$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);
回答by Divisible
Repeated Question. Search before posting. PHP library that can list contents of zip / rar files
重复的问题。发帖前先搜索。 可以列出 zip/rar 文件内容的 PHP 库
<?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);
?>