如何使用 PHP 读取 .tar.gz 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4878792/
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
How can I read a .tar.gz file with PHP?
提问by Michael
I am building a system for people to upload .tar (and .tar.gz, .tar.bz2, .zip, etc) files in PHP. Uploading the files is fine, but I would like to list files contained in the archive after it has been uploaded.
我正在构建一个系统,供人们在 PHP 中上传 .tar(和 .tar.gz、.tar.bz2、.zip 等)文件。上传文件很好,但我想在上传后列出存档中包含的文件。
Can someone recommend a good PHP library that can read file archives?
有人可以推荐一个可以读取文件档案的好的PHP库吗?
I found File_Archiveon Pear but it hasn't been updated in a few years. ZipArchive works great for .zip files, but I need something that can handle more file types.
我在 Pear 上找到了File_Archive,但它已经几年没有更新了。ZipArchive 非常适合 .zip 文件,但我需要可以处理更多文件类型的东西。
updateI'm running on RHEL6, PHP 5.2, and Apache 2.2.
更新我在 RHEL6、PHP 5.2 和 Apache 2.2 上运行。
回答by Arnaud Le Blanc
You can do this with the PharData
class:
你可以用这个PharData
类来做到这一点:
// Example: list files
$archive = new PharData('/some/file.tar.gz');
foreach($archive as $file) {
echo "$file\n";
}
This even works with the phar://
stream wrapper:
这甚至适用于phar://
流包装器:
$list = scandir('phar:///some/file.tar.gz');
$fd = fopen('phar:///some/file.tar.gz/some/file/in/the/archive', 'r');
$contents = file_get_contents('phar:///some/file.tar.gz/some/file/in/the/archive');
If you don't have Phar, check the PHP-only implementation, or the pecl extension.
如果您没有 Phar,请检查PHP-only implementation或pecl extension。
回答by mario
Don't try to build this yourself. Use an existing class like http://pear.php.net/package/Archive_Tarto handle that for you.
不要试图自己构建它。使用像http://pear.php.net/package/Archive_Tar这样的现有类来为您处理。
回答by shasi kanth
The below code reads a file inside a .gzzip file
下面的代码读取.gzzip 文件中的文件
<?php
$z = gzopen('zipfile.gz','r') or die("can't open: $php_errormsg");
$string = '';
while ($line = gzgets($z,1024)) {
$string .= $line;
}
echo $string;
gzclose($z) or die("can't close: $php_errormsg");
?>
Notethat you need to have the zip extension of php enabled for this code to work.
请注意,您需要启用 php 的 zip 扩展才能使此代码工作。
回答by Jerry
I don't think the first answer works. Or it only doesn't work for me. You could not read file content when you foreach it. I give my working code below.
我不认为第一个答案有效。或者它只对我不起作用。使用 foreach 时无法读取文件内容。我在下面给出了我的工作代码。
$fh = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator('phar:///dir/file.tar.gz'),
RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($fh as $splFileInfo) {
echo file_get_contents($splFileInfo->getPathname());
}
This works for gz, zip, tar and bz files.
这适用于 gz、zip、tar 和 bz 文件。