天天看點

PHP 壓縮檔案為zip

從網上複制的代碼你往往會發現沒有效果,因為

ZipArchive :: open()的參數2為ZipArchive :: OVERWRITE的時候,當目标檔案已經存在時,程式會生成一個新的同名檔案覆寫原來的檔案,但是,當這個檔案不存在時,ZipArchive ::打開( )将傳回數字9,是常量ZipArchive :: ER_NOENT的整數值,錯誤資訊是“沒有這樣的檔案。”。

如果想要實作檔案存在時自動覆寫檔案不存在時自動建立,那麼應該同時使用ZipArchive :: OVERWRITE和ZipArchive :: CREATE,這樣是比較實用的,在沒有的時候會自動建立

實作:

$zip=new ZipArchive;
        if($zip->open('聯通-440.zip', ZipArchive::OVERWRITE | ZipArchive :: CREATE) === TRUE){
            $zip->addFile('聯通-440.txt');//假設加入的檔案名是image.txt,在目前路徑下
            $zip->close();
        }
           

附贈壓縮檔案夾實作:

function index(){
    $zip = new ZipArchive();
        if ($zip->open('test.zip', ZipArchive::OVERWRITE | ZipArchive :: CREATE) === TRUE) {
            $this->addFileToZip('./log/', $zip); //調用方法,對要打包的根目錄進行操作,并将ZipArchive的對象傳遞給方法
            $zip->close(); //關閉處理的zip檔案
        }
}

    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);
    }
           

$path 傳入的是檔案夾的路徑