PHP从zip文件目录中读取文本文件

时间:2010-12-13 10:16:37

标签: php file zip

我有一个包含一组压缩文件的目录。 每个文件都包含foo.txt文件。

如何从每个zip中读取此文本文件?

我知道glob用于列出目录中的所有文件

4 个答案:

答案 0 :(得分:4)

PHP有an extension,允许您使用ZIP存档。

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

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

答案 1 :(得分: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";   
        }
}

答案 2 :(得分:1)

据我所知,无法以这种方式访问​​压缩数据,您必须先将其解压缩。

如果您感觉舒服,可以使用此PHP扩展程序:http://www.php.net/manual/en/book.zip.php

答案 3 :(得分:1)

您是否看过P HP5's ZipArchive functions?

// 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 question: https://stackoverflow.com/questions/4085333/modifying-a-single-text-file-in-a-zip-file-in-php

相关问题