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

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

问题描述:

I have a directory which contains a set of zipped files. each of these files has foo.txt file in it.

How can I read this text file from each zip?

I know glob is used to list all files from the directory

我有一个目录,其中包含一组压缩文件。 each这些文件中包含foo.txt文件 。 p>

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

我知道 glob code>用于列出所有文件 来自目录 p> div>

PHP has an extension that allows you to work with ZIP archives.

Note that to access that one file you don't need to unzip the whole archive. The ZipArchive::extractTo method allows you to specify what to extract.

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

As far as I know compressed data can't be accessed this way, and you'd have to unzip it first.

If you're comfortable though, you can use this PHP extension: http://www.php.net/manual/en/book.zip.php

You can use the PHP zip extension as:

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","
";
        } else {
                echo "Failed to open $zipFile","
";   
        }
}

Have you taken a look at PHP5'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

A helpfull SO question: https://stackoverflow.com/questions/4085333/modifying-a-single-text-file-in-a-zip-file-in-php