php的ZipArchive类用法实例_PHP

WBOY
Release: 2016-05-31 19:29:14
Original
848 people have browsed it

本文实例讲述了php的ZipArchive类用法,分享给大家供大家参考。具体如下:

通常来说,php5.2开始支持ZipArchive类,php4只能使用zip函数。其实在官方实现zip类之前,已经有大牛贡献了打包解压zip文件的方法。现在php包含了ZipArchive类,当然优先使用。使用该类能创建和解压zip文件,也能直接读取zip压缩包内的内容,很方便,这里主要总结下读取和解压的过程。

解压一个包到指定目录:

代码如下:

$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
    $zip->extractTo('/my/destination/dir/');
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}
?>


如果只是需要读取包中某个文件的内容,需要文件名或者文件的索引值。

代码如下:

$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
    echo $zip->getFromName('example.php');
    $zip->close();
}
?>


如果example.php在某目录下,获取内容时需要加上路径。

如果只知道文件名,而不知到文件的具体路径,可以搜索指定文件名的索引,再依靠索引获取内容。

代码如下:

$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
    $index=$zip->locateName('example.php', ZIPARCHIVE::FL_NOCASE|ZIPARCHIVE::FL_NODIR);
    $contents = $zip->getFromIndex($index);
}
?>


上面获取索引依靠 locateName方法,如果压缩包内多个路径下有同名文件,好像只能返回第一个的索引,如果要获取所有同名文件的索引,只能使用笨办法,循环搜索。

代码如下:

$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
    for($i = 0; $i numFiles; $i++)
      {
           if(substr_count($zip->getNameIndex($i), 'example.php')>0){
                $contents = $zip->getFromIndex($i);                           
            }
       }
}
?>

希望本文所述对大家的php程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!