开发者

PHP read a text file from a directory of zip files

开发者 https://www.devze.com 2023-01-30 12:01 出处:网络
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 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 file开发者_开发问答s 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 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

0

精彩评论

暂无评论...
验证码 换一张
取 消