我正在使用PHP构建一个系统,让人们上传.tar(以及.tar.gz,.tar.bz2,.zip等)文件。上传文件没有问题,但是我想在上传后列出存档中包含的文件。
有人能推荐一个可以读取文件归档的好的PHP库吗?
我在 Pear 中找到了File_Archive,但它已经好几年没有更新了。ZipArchive 对于.zip文件非常好用,但我需要处理更多的文件类型。
更新 我正在运行RHEL6,PHP 5.2和Apache 2.2。
我正在使用PHP构建一个系统,让人们上传.tar(以及.tar.gz,.tar.bz2,.zip等)文件。上传文件没有问题,但是我想在上传后列出存档中包含的文件。
有人能推荐一个可以读取文件归档的好的PHP库吗?
我在 Pear 中找到了File_Archive,但它已经好几年没有更新了。ZipArchive 对于.zip文件非常好用,但我需要处理更多的文件类型。
更新 我正在运行RHEL6,PHP 5.2和Apache 2.2。
PharData
类来实现此操作。// Example: list files
$archive = new PharData('/some/file.tar.gz');
foreach($archive as $file) {
echo "$file\n";
}
这甚至适用于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');
如果您没有Phar,请检查“仅PHP实现”的PHP-only implementation或者pecl扩展。->listContent
方法和其他方法。 - mario <?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");
?>
注意:在运行该代码前,您需要启用php的zip扩展。
我认为第一个答案不可行,或者只有对我无效。当您使用foreach循环时,无法读取文件内容。下面是我的有效代码。
$fh = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator('phar:///dir/file.tar.gz'),
RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($fh as $splFileInfo) {
echo file_get_contents($splFileInfo->getPathname());
}
echo shell_exec('tar -tf <path/to/file.tgz>');// lists the contents of a Gzipped Tarball