Heim  >  Artikel  >  Backend-Entwicklung  >  php的ZipArchive类用法实例_PHP

php的ZipArchive类用法实例_PHP

WBOY
WBOYOriginal
2016-05-31 19:29:14842Durchsuche

本文实例讲述了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程序设计有所帮助。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn