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

yipeiwu_com6年前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】的支持。

相关文章

PHP 金额数字转换成英文

复制代码 代码如下:<?php $num=1220.01; echo fmoney($num);//结果:1,220.21 echo umoney($num); //结果:ONE...

php字符串分割函数用法实例

本文实例讲述了php字符串分割函数用法。分享给大家供大家参考。具体分析如下: php中explode 和 split 函数用来分割字符串。 explode函数语法如下 explode...

php str_pad 函数使用详解

string str_pad ( string , int pad_length , string pad_string , int pad_type); string 指定字符串,pa...

php安全之直接用$获取值而不$_GET 字符转义

复制代码 代码如下: <? function my_addslashes($string, $force = 0) { !defined('MAGIC_QUOTES_GPC') &...

PHP 冒泡排序算法的实现代码

基本概念 冒泡排序的基本概念是:依次比较相邻的两个数,将小数放在前面,大数放在后面。即首先比较第1 个和第2个数,将小数放前,大数放后。然后比较第2个数和第3个数,将小数放前,大数放后,...