php zip压缩文件

 <?php
       $za = new ipArchive();
        $filePath = storage_path('app/public/') . '2.zip';// 压缩包所在的位置路径
        $za->open($filePath, ipArchive::CREATE|ipArchive::OVERWRITE);
        $file =storage_path('app/public/').'nodes.txt';
        if( true === $za->addFile($file,basename($file))){
//            unlink($file);
        }
        if(!$za->close()){
            echo 'failure.';
        }
        return success_json("ok");

 引入包  如果压缩包文件存在,关闭的时候就会报错

ZipArchive::close(): Renaming temporary file failed: Permission denied in file
可以把多个文件加入压缩包,进行处理

  

<?php
//多个文件压缩
     $zip = new ipArchive();
        $filePath = storage_path('app/public/') . '4.zip';// 压缩包所在的位置路径
        $zip->open($filePath, ipArchive::CREATE|ipArchive::OVERWRITE);
        for($i=0;$i<10;$i++){
            $files[]=storage_path('app/public/').$i.'.txt';
        }
        foreach($files as $k =>$file){
            $zip->addFile($file,basename($file));   //向压缩包中添加文件
        }
//        if( true === $zip->addFile($file,basename($file))){
////            unlink($file);
//        }
        if(!$zip->close()){
            echo 'failure.';
        }
        foreach ($files as $file) {
            unlink($file);
        }
        return success_json("ok");

 

 压缩处理逻辑是 先把文件读取到然后,压缩到指定文件,并且把对应被压缩文件清除掉,便于把多余的文件占空间

原文地址:https://www.cnblogs.com/kevin-yang123/p/15165612.html