php ZipArchive实现多文件打包下载实例

yipeiwu_com5年前PHP代码库

实例代码:

public function downLoad($dataUrl,$saveName)
  {
    $datalist = [
      ROOT_PATH.'/public/introduce/110.docx',
      ROOT_PATH.'/public/upfile/110.zip'
    ];
//    print_r($datalist);die;
    $filename = ROOT_PATH.'\public\/'.$saveName.'.zip';
    if(file_exists($filename)){
      unlink($filename);
    }

    $zip = new \ZipArchive();
    if ($zip->open($filename,\ZipArchive::CREATE)!== true){
      exit('无法打开文件,或者文件创建失败');
    }

    foreach ($dataUrl as $index => $item) {
      if (DIRECTORY_SEPARATOR=='\\'){
        $item = str_replace('/',DIRECTORY_SEPARATOR,$item);
        $filename = str_replace('/',DIRECTORY_SEPARATOR,$filename);
      }
//      var_dump($item);
//      var_dump(file_exists($item));die;
      if (file_exists($item)){
        $zip->addFile($item,basename($item));
      }
    }

    $zip->close();
    if(!file_exists($filename)){
      exit("无法找到文件"); //即使创建,仍有可能失败
    }
    header('Content-Type: application/zip');
    header('Content-disposition: attachment; filename='.basename($filename));
    header('Content-Length: ' . filesize($filename));
    @readfile($filename);
     @unlink ( $filename );
}

注意:里面的路径全部用绝对路径,不然会找不到文件

附赠其他操作:

解压缩zip文件

public function unzip_file($file, $dir){ 

    // 实例化对象 

    $zip = new ZipArchive() ; 

    //打开zip文档,如果打开失败返回提示信息 

    if ($zip->open($file) !== TRUE) { 

     die ("Could not open archive"); 

    } 

    //将压缩文件解压到指定的目录下 

    $zip->extractTo($dir); 

    //关闭zip文档 

    $zip->close(); 

  }

获取解压文件目录

public function loopFun($dir) 

  { 

    $handle = opendir($dir.".");

    //定义用于存储文件名的数组

    $array_file = array();

    while (false !== ($file = readdir($handle)))

    {

      if ($file != "." && $file != "..") {

        $array_file[] = $dir.'/'.$file; //输出文件名

      }

    }

    closedir($handle);

    return $array_file;

    //print_r($array_file);

  }

大家可以在本地测试下,感谢大家的学习和对【宜配屋www.yipeiwu.com】的支持。

相关文章

ThinkPHP5 验证器的具体使用

ThinkPHP5 验证器的具体使用

前言: 我们在做API开发的时候,我们会接受客户端传来的参数,大家都知道这个参数是不可信的,我们后端开发人员必须对这个参数进行验证。我在之前的开发中只是知道tp5的验证器,并不知道他的用...

PHP5多态性与动态绑定介绍

什么是多态性? 多态性是继数据抽象和继承后,面向对象语言的第三个特征。从字面上理解,多态的意思是“多种形态”,简单来说,多态是具有表现多种形态的能力的特征,在OO中是指“语言具有根据对象...

Godaddy空间Zend Optimizer升级方法

但今天在安装测试程序的时候提示zend Optimizer not installed.这让我很迷茫,这么普遍的空间为什么没有安装zend了,然后我查看info.php,我惊奇的发现,服...

setcookie中Cannot modify header information-headers already sent by错误的解决方法详解

复制代码 代码如下:<?php   setcookie("username","bu",time()+3600);   echo "aaaa...

php session和cookie使用说明

1. PHP的COOKIE cookie 是一种在远程浏览器端储存数据并以此来跟踪和识别用户的机制。PHP在http协议的头信息里发送cookie, 因此setcookie() 函数必须...