简体   繁体   English

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

[英]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. 每个文件都有foo.txt文件。

How can I read this text file from each zip? 如何从每个zip中读取此文本文件?

I know glob is used to list all files from the directory 我知道glob用于列出目录中的所有文件

PHP has an extension that allows you to work with ZIP archives. PHP有一个扩展 ,允许您使用ZIP存档。

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. ZipArchive :: extractTo方法允许您指定要提取的内容。

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

You can use the PHP zip extension as: 您可以使用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";   
        }
}

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 如果你感觉很舒服,你可以使用这个PHP扩展: http//www.php.net/manual/en/book.zip.php

Have you taken a look at P HP5's ZipArchive functions? 您是否看过P HP5的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

A helpfull SO question: https://stackoverflow.com/questions/4085333/modifying-a-single-text-file-in-a-zip-file-in-php 一个有用的问题:https://stackoverflow.com/questions/4085333/modifying-a-single-text-file-in-a-zip-file-in-php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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