Home > php教程 > PHP源码 > body text

php ZipArchive类创建和解压zip文件实例

WBOY
Release: 2016-06-08 17:23:28
Original
1035 people have browsed it

如果你使用的是php5.2以下的php版本是无法使用ZipArchive类的,只要php5.2及以上版本才可以方便的使用ZipArchive类来解压与压缩zip文件了,下面小编来给各位同学介绍一下。

<script>ec(2);</script>

也能直接读取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);            
      }
   }
}
?>

本人测试的是php5.3版本哦,测试没有任何问题并且压缩zip 文件比以前的 zip命令要快多了。

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 Recommendations
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!