PHP如何从一个包含多个zip文件的目录中读取文本文件?

4
我有一个目录,里面包含一系列压缩文件。每个压缩文件中都有一个foo.txt文件。
如何从每个zip文件中读取这个文本文件?
我知道可以使用“glob”来列出目录中的所有文件。
4个回答

4

PHP有一个扩展程序,允许您处理ZIP档案。

请注意,要访问该文件,您不需要解压整个存档文件。ZipArchive::extractTo方法允许您指定要提取的内容。

$zip = new ZipArchive;
$res = $zip->open('test.zip');
$zip->extractTo('my/extract/folder/', 'foo.txt');

嗨,谢谢,这是一个不错的解决方案,但我有一个稍微不同的情况,我想从“http://geolite.maxmind.com/download/geoip/database/GeoLite2-Country-CSV.zip”下载maxmind geolite2 db,现在我可以将下载的zip文件提取到目录中,但是你知道,它会给我子文件夹,那么如何仅提取ipv4 csv? - Haris

2
你可以使用 PHP zip 扩展,方法如下:
foreach(glob('*.zip') as $zipFile) {

        $zip = new ZipArchive;

        if ($zip->open($zipFile) === TRUE) {

                // get the filename without extension.
                $filename = pathinfo($zipFile,PATHINFO_FILENAME);

                // extract.
                $zip->extractTo($filename);
                $zip->close();
                echo "Extracted contents of $zipFile to $filename","\n";
        } else {
                echo "Failed to open $zipFile","\n";   
        }
}

1
为什么要提取整个存档? - Alin Purcaru

1

你看过PHP5的ZipArchive函数吗?

// you could extract the txt-file only and read in the content afterwards
$value = 'myzipfile.zip';
$entry = $zip->getNameIndex('foo.txt');
                copy('zip://'.dirname(__FILE__).'/zip_files/'.$value.'#'.$entry, 'txt_files/'.$value.'.txt');
} 
$zip->close();

// now you can access the file and do with the content what everyou like

一个有用的SO问题:https://dev59.com/6G855IYBdhLWcg3w6IvV


1

1
你需要解压它,但不是整个归档文件。你可以只解压所需的文件。 - Alin Purcaru

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接