您的位置:首页 > 编程语言 > PHP开发

php生成压缩包和打开压缩包

2017-06-15 15:23 295 查看
需呀用到ZipArchive类,php默认带的有,废话不说,直接上代码,亲测可以使用,先来个生成压缩包,解压缩包后边补上

开启PHP支持ZipArchive

在php.ini文件中将extension=php_zip.dll  开头的;的去掉,重启www服务器就可以了

1:对多个文件生成压缩包

<?php

//生成压缩文件

function createzip($files = array(),$destination = '',$overwrite = false){

if(file_exists($destination) && !$overwrite) { return false; }

$valid_files = array();

if(is_array($files)) {

foreach($files as $file) {

if(file_exists($file['file'])) {

$valid_files[] = $file;

}

}

}

if(count($valid_files)) {

$zip = new ZipArchive();

if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {

return false;

}

foreach($valid_files as $file) {

$zip->addFile($file['file'],$file['fn']);

}

$zip->close();

return file_exists($destination);

}else{

return false;

}

}

//生成压缩文件

$files=array(array('file'=>'27.txt','fn'=>'test.txt'));

file:源文件名称,最好带路径,比如/data/27.txt

fn:生成的压缩文件里文件的名称,不用带路径

$newZip = '12.zip';//生成的压缩文件名称

createzip($files,$newZip,true);

2:对文件夹生成压缩包

function
createDirZip($path,$zip){

    $handler=opendir($path);

    while(($filename=readdir($handler))!==false){

        if($filename != "." && $filename != ".."){//文件夹文件名字为'.'和‘..’,不要对他们进行操作

            if(is_dir($path."/".$filename)){// 如果是文件夹则继续递归执行

                addFileToZip($path."/".$filename, $zip);

            }else{

                $zip->addFile($path."/".$filename);

            }

        }

    }

    @closedir($path);

}

$zip=new ZipArchive();

if($zip->open('test.zip', ZipArchive::OVERWRITE)=== TRUE){

    createDirZip('test', $zip);

    $zip->close();

}

ZipArchive的使用请查看官方文档:http://php.net/manual/zh/class.ziparchive.php

3:解压缩

<?php

$file = 'test.zip';

function get_zip_file($filename, $path) {

 if(!file_exists($filename)){

  die("文件 $filename 不存在!");

 }

 $filename = iconv("utf-8","gb2312",$filename);//根据实际情况看需不需要转码

 $path = iconv("utf-8","gb2312",$path);//根据实际情况看需不需要转码

 //打开压缩包

 $resource = zip_open($filename);

 //遍历读取压缩包里面的一个个文件

 while ($dir_resource = zip_read($resource)) {

  //如果能打开则继续

  if (zip_entry_open($resource,$dir_resource)) {

   //获取压缩包里面当前对应的文件名

   $file_name = $path.zip_entry_name($dir_resource);

   //以最后一个“/”分割,再用字符串截取出路径部分

   $file_path = substr($file_name,0,strrpos($file_name, "/"));

   //如果路径不存在,则创建一个目录,true表示可以创建多级目录,这个很好用

   if(!is_dir($file_path)){

    mkdir($file_path,0777,true);

   }

   //如果不是目录,则写入文件

   if(!is_dir($file_name)){

    //读取这个文件的大小

    $file_size = zip_entry_filesize($dir_resource);

    //这里可以限制读取解压的文件大小范围,太大的话会比较慢

     $file_content = zip_entry_read($dir_resource,$file_size);

     file_put_contents($file_name,$file_content);

   }

   //关闭当前打开的资源

   zip_entry_close($dir_resource);

  }

 }

 //关闭压缩包

 zip_close($resource);

}

get_zip_file($file,'./');

zip官方文档:http://php.net/manual/zh/ref.zip.php
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: