thinkphp5批量生成文件并压缩之后导出

php导出 批量导出文件 批量生成文件 PHP下载 php生成zip PHP生成压缩包 ZipArchive

thinkphp5批量生成文件,然后把文件夹打包成zip输出到浏览器下载,注意加粗部分:

public function explodeData()

    {

        $templateList    = $this->dbConfig->table('data')->select();

        if(!$templateList){

            $this->error('数据为空');

         }

         foreach ($templateList as $key => $value) {

            $path = ROOT_PATH . DS . 'runtime/savedata/temp_'.$value['id'].'.txt';

            $fp=fopen($path,"w+");

            fwrite($fp,$value['info']);

            fclose($fp);

         }

         $zip = new \ZipArchive;

         $filename = ROOT_PATH . DS .'runtime/data.zip';

         if($zip->open($filename, \ZIPARCHIVE::CREATE)===TRUE) {

            $this->addFileToZip(ROOT_PATH . DS .'runtime/savedata'. DS, $zip); //调用方法,对要打包的根目录进行操作,并将ZipArchive的对象传递给方法

            $zip->close(); //关闭处理的zip文件

         }

         if(!file_exists($filename)){   

            exit("无法找到文件"); //可能创建失败

         }

        header("Cache-Control: public"); 

        header("Content-Description: File Transfer"); 

        header('Content-disposition: attachment; filename='.basename($filename)); //文件名   

        header("Content-Type: application/zip"); //zip格式的   

        header("Content-Transfer-Encoding: binary"); //告诉浏览器,这是二进制文件    

        header('Content-Length: '. filesize($filename)); //告诉浏览器,文件大小   

        @readfile($filename);

    }


    public function addFileToZip($path,$zip){

        $handler=opendir($path); //打开当前文件夹由$path指定。

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

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

                if(is_dir($path."/".$filename)){// 如果读取的某个对象是文件夹,则递归

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

                }else{ //将文件加入zip对象

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

                }

            }

        }

        @closedir($path);

    }



参考:

https://lvtao.net/dev/php_zip.html

https://zhidao.baidu.com/question/984742898850376139.html