ziparchive类是专门用于文件的压缩与解压操作的类,通过压缩文件可以达到节省磁盘空间的目的,并且压缩文件体积更小,便于网络传输。

在ziparchive类中我们主要使用如下方法:

1:open(打开一个压缩包文件)

$zip = new \ziparchive;

$zip->open('test_new.zip', \ziparchive::create)

参数说明:

第一个参数:要打开的压缩包文件

第二个参数:

ziparchive::overwrite总是创建一个新的文件,如果指定的zip文件存在,则会覆盖掉。

ziparchive::create如果指定的zip文件不存在,则新建一个。

ziparchive::excl如果指定的zip文件存在,则会报错。

ziparchive::checkcons对指定的zip执行其他一致性测试。

2:addfile(将指定文件添加到压缩包中)

//将test.txt文件添加到压缩包中

$zip->addfile('test.txt'); //第二个参数可对文件进行重命名

3:addemptydir (将指定空目录添加到压缩包中)

//将一个空的目录添加到zip中

 $zip->addemptydir ('newdir');

4:addfromstring(将指定内容的文件添加到压缩包)

// 将有指定内容的new.txt文件添加到zip文件中

$zip->addfromstring('new.txt', '要添加到new.txt文件中的文本');

5:extractto(将压缩包解压到指定目录)

$zip->extractto('test');

6:getnameindex(根据索引返回文件名称)

$zip->getnameindex(0);//返回压缩包中索引为0的文件名称

7:getstream(根据压缩内的文件名称,获取该文件的文本流)

$zip->getstream('hello.txt');

8:renameindex(根据压缩文件内的索引(从0开始)修改压缩文件内的文件名)

/把压缩文件内第一个文件修改成newname.txt

$zip->renameindex(0,'newname.txt');

9:renamename(根据压缩文件内的文件名,修改压缩文件内的文件名)

//把压缩文件内的word.txt修改成newword.txt

$zip->renamename('word.txt','newword.txt');

10:deleteindex (根据压缩文件内的索引删除压缩文件内的文件)

//把压缩文件内第一个文件删除

$zip->deleteindex (0);

11:deletename(根据压缩文件内的文件名删除文件)

//把压缩文件内的word.txt删除

$zip->deletename('word.txt');

上面是ziparchive类的一些常用方法,下面来介绍一些简单示例:

一:创建一个压缩包

$zip = new \ziparchive;

if ($zip->open('test_new.zip', \ziparchive::create) === true)

{

 // 将指定文件添加到zip中

 $zip->addfile('test.txt');

  

 // test.txt文件添加到zip并将其重命名为newfile.txt

 $zip->addfile('test.txt', 'newfile.txt');

  

 // 将test.txt文件添加到zip文件中的test文件夹内

 $zip->addfile('test.txt', 'test/newfile.txt');

  

 //将一个空的目录添加到zip中

 $zip->addemptydir ('test');

  

 // 将有指定内容的new.txt文件添加到zip文件中

 $zip->addfromstring('new.txt', '要添加到new.txt文件中的文本');

  

 // 将有指定内容的new.txt添加到zip文件中的test文件夹

 $zip->addfromstring('test/new.txt', '要添加到new.txt文件中的文本');

  

 //将images目录下所有文件添加到zip中

  if ($handle = opendir('images')){

   // 添加目录中的所有文件

   while (false !== ($entry = readdir($handle))){

    if ($entry != "." && $entry != ".." && !is_dir('images/' . $entry)){

      $zip->addfile('images/' . $entry);

    }

   }

   closedir($handle);

  }

  

 // 关闭zip文件

 $zip->close();

}

二:获取压缩包的文件信息并解压指定压缩包

$zip = new \ziparchive;

if ($zip->open('test_new.zip') === true) {

 //获取索引为0的文件名称

 var_dump($zip->getnameindex(0));

  

 //将压缩包文件解压到test目录下

 $zip->extractto('test');

  

 //获取压缩包指定文件的文本流

 $stream = $zip->getstream('test.txt');

  

 // 关闭zip文件

 $zip->close();

 $str = stream_get_contents($stream); //这里注意获取到的文本编码

 var_dump($str);

}

三:修改压缩包内指定文件的文件名称及删除压缩包内指定文件

$zip = new \ziparchive;

if ($zip->open('test_new.zip') === true) {

 //把压缩文件内索引为0的文件修改成newname.txt

 $zip->renameindex(0,'newname.txt');

 //把压缩文件内的new.txt修改成newword.txt

 $zip->renamename('new.txt','newword.txt');

 //删除压缩文件内索引为0的文件

 $zip->deleteindex(0);

 //删除压缩文件的test.png

 $zip->deletename('test.png');

 // 关闭zip文件

 $zip->close();

}

以上就是php利用ziparchive类实现文件压缩与解压的详细内容,感谢大家的学习和对www.887551.com的支持。