PHP ZipArchive壓縮資料夾教學(源碼講解)

用php壓縮資料夾是日常工作的一部分,下面以真實源碼講解

<?php

// 示例源碼壓縮指定文件夾,壓縮後的文件與源文件夾在相同的位置
$fn = "filename1.zip"; // 壓縮後的文件名
$fd = "/Volumes/folde1"; // 要壓縮的文件夾,這個是linux路徑,在windows類似 c:\folder1

zipFolder($fd.DIRECTORY_SEPARATOR.$fn, $fd.DIRECTORY_SEPARATOR.$fn);

function zipFolder($folder, $zipFileName)
{
    // Get real path for our folder php文件運行於apache或nginx等服務器環境,需要獲取物理路徑
    $rootPath = realpath($folder);

    // Initialize archive object 初始化ZipArchive對象
    $zip = new ZipArchive();
    $zip->open($zipFileName, ZipArchive::CREATE | ZipArchive::OVERWRITE); // 創建壓縮文件

    // Create recursive directory iterator 獲得遞歸訪問器,支持多級子目錄
    /** @var SplFileInfo[] $files */
    $files = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($rootPath),
        RecursiveIteratorIterator::LEAVES_ONLY
    );

    foreach ($files as $name => $file) { 
        // Skip directories (they would be added automatically) 跳過目錄,會自動處理(壓縮文件的時候帶路徑就會有目錄)
        if (!$file->isDir()) {
            // Get real and relative path for current file 獲得文件物理路徑
            $filePath = $file->getRealPath();
            $relativePath = substr($filePath, strlen($rootPath) + 1);

            // Add current file to archive 加入壓縮
            $zip->addFile($filePath, $relativePath);
        }
    }

    // Zip archive will be created only after closing object 關閉後寫入
    $zip->close();
}

php運行環境要已經安裝zip擴展哦

以上就是PHP ZipArchive壓縮資料夾教學,如有不清楚的請留言。

延伸閱讀:如果您正在尋找一款整合了GEO分析、GSC整合、關鍵字排名追蹤和AI智能SEO審計的全能型SEO工具,推薦試試 Yseo — AI SEO Tool

Alex Lin

Leave a Reply

Your email address will not be published. Required fields are marked *