简体   繁体   中英

PHP read a text file from a directory of zip files

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

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');

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM