萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 文件編碼批量轉換工具類:支援目錄遞歸、GBK/UTF-8 互轉

需求背景

老項目遷移、團隊協作、開源庫整合等場景常面臨編碼不一致問題:GBK/GB2312 歷史文件需統一轉為 UTF-8,或反之。手動轉換效率低且易出錯,需一個健壯的批量轉換工具,支援單文件/目錄、遞歸遍歷、讀寫權限檢查、編碼驗證。

核心類設計:ConvertEncode

依賴擴展:mbstring(必須)、filesystem(可選)。核心功能:

  • 單文件 / 目錄批量轉換
  • 目錄遞歸遍歷可選
  • 源編碼與目標編碼任意指定
  • 編碼合法性檢查(避免重複轉換導致亂碼)
  • 異常處理機制(自定義 ConvertException)

完整類代碼

<?php
/**
 * 文件編碼批量轉換工具
 * @example
 * $convert = new ConvertEncode();
 * try {
 *     $convert->setPath('/path/to/project', true, true); // 目錄、遞歸
 *     $convert->setEncode('GBK', 'UTF-8');
 *     $convert->convert();
 * } catch (ConvertException $e) {
 *     echo $e->getMessage();
 * }
 */
class ConvertEncode {
    private $_to_encoding;
    private $_from_encoding;
    private $_path;
    private $_directory = false;
    private $_recursion = false;
    private $_files = [];

    public function __construct() {
        if (!function_exists('mb_convert_encoding')) {
            throw new ConvertException('mbstring extension is required');
        }
    }

    /** 設置轉換路徑:文件或目錄 */
    public function setPath(string $path, bool $is_dir = false, bool $rec = false): bool {
        $this->_path = $path;
        $this->_directory = $is_dir;
        $this->_recursion = $rec;
        return true;
    }

    /** 設置編碼:來源 -> 目標 */
    public function setEncode(string $from, string $to): bool {
        $this->_from_encoding = $from;
        $this->_to_encoding = $to;
        return true;
    }

    /** 執行轉換入口 */
    public function convert(): bool {
        return $this->_directory ? $this->_convertDirectory() : $this->_convertFile();
    }

    /** 單文件轉換 */
    private function _convertFile(): bool {
        if (!file_exists($this->_path)) {
            throw new ConvertException("{$this->_path} does not exist.");
        }
        if (!is_file($this->_path)) {
            throw new ConvertException("{$this->_path} is not a file.");
        }
        if (!$this->_isWR()) {
            throw new ConvertException("{$this->_path} must be readable and writable.");
        }

        $realPath = realpath($this->_path);
        $content = file_get_contents($realPath);
        
        // 關鍵:檢查源編碼合法性,防止重複轉換
        if (mb_check_encoding($content, $this->_from_encoding)) {
            $converted = mb_convert_encoding($content, $this->_to_encoding, $this->_from_encoding);
            file_put_contents($realPath, $converted);
        }
        return true;
    }

    /** 目錄批量轉換 */
    private function _convertDirectory(): bool {
        if (!file_exists($this->_path) || !is_dir($this->_path)) {
            throw new ConvertException("{$this->_path} is not a valid directory.");
        }
        if (!$this->_isWR()) {
            throw new ConvertException("{$this->_path} must be readable and writable.");
        }

        $this->_scanDirFiles();
        if (empty($this->_files)) {
            throw new ConvertException("{$this->_path} is empty.");
        }

        foreach ($this->_files as $file) {
            $content = file_get_contents($file);
            if (mb_check_encoding($content, $this->_from_encoding)) {
                $converted = mb_convert_encoding($content, $this->_to_encoding, $this->_from_encoding);
                file_put_contents($file, $converted);
            }
        }
        return true;
    }

    /** 檢查讀寫權限 */
    private function _isWR(): bool {
        return is_readable($this->_path) && is_writable($this->_path);
    }

    /** 遞歸掃描目錄收集文件 */
    private function _scanDirFiles(string $dir = ''): bool {
        $base = empty($dir) ? realpath($this->_path) . DIRECTORY_SEPARATOR : realpath($dir) . DIRECTORY_SEPARATOR;
        $entries = empty($dir) ? scandir($this->_path) : scandir($dir);

        foreach ($entries as $entry) {
            if ($entry === '.' || $entry === '..' || $entry[0] === '.') continue; // 跳過隱藏文件
            
            $fullPath = $base . $entry;
            if (is_dir($fullPath)) {
                if ($this->_recursion) $this->_scanDirFiles($fullPath);
            } elseif (is_file($fullPath)) {
                $this->_files[] = $fullPath;
            }
        }
        return true;
    }
}

/** 自定義異常 */
class ConvertException extends Exception {}

使用示例

<?php
require_once 'ConvertEncode.php';

$convert = new ConvertEncode();
try {
    // 場景 1:單文件轉換
    $convert->setPath('./config.php');
    $convert->setEncode('GBK', 'UTF-8');
    $convert->convert();
    echo "單文件轉換完成\n";

    // 場景 2:目錄遞歸轉換(老項目整體遷移)
    $convert->setPath('./legacy_src', true, true);
    $convert->setEncode('GB2312', 'UTF-8');
    $convert->convert();
    echo "目錄遞歸轉換完成\n";

} catch (ConvertException $e) {
    echo "轉換失敗: " . $e->getMessage();
}

關鍵技術點解析

1. mb_check_encoding() 守衛重複轉換

作者原文提到「檢測編碼失敗,GBK 和 UTF-8 都返回 true」。實際上 mb_check_encoding($str, 'GBK') 在字符串**確實是合法 GBK** 時返回 true,若字符串已是 UTF-8 但剛好也符合 GBK 字節規則(極少見),會誤判。工程上常用策略:

  • 強制指定源編碼,由人工確認(如項目已知為 GBK)。
  • 引入 mb_detect_encoding() 輔助判斷,但不可完全依賴。
  • **最佳實踐**:轉換前備份、轉換後抽樣驗證、版本控制(Git)可回滾。

2. 遞歸遍歷與隱藏文件過濾

_scanDirFiles() 使用 scandir() 而非 glob(),兼容性更好;跳過 .、..、點開頭隱藏文件(如 .git、.env),避免污染版本控制目錄。

3. 異常體系設計

自定義 ConvertException 繼承 Exception,調用方可精準捕獲轉換錯誤,區別於系統級異常。

擴展建議

  • 乾跑模式:新增 --dry-run 參數,僅掃描列出將被轉換文件,不實際寫入。
  • 編碼自動偵測:集成 mb_detect_encoding() + 置信度閾值,支援「未知編碼 → UTF-8」。
  • 並發處理:大量文件時使用 pcntl_fork 或 parallel 擴展多進程轉換。
  • BOM 處理:UTF-8 轉換時可選是否寫入 BOM(chr(0xEF).chr(0xBB).chr(0xBF))。

總結

ConvertEncode 類提供了生產可用的文件編碼批量轉換基礎設施,核心優勢在於:權限校驗、編碼合法性守衛、遞歸遍歷、異常隔離。配合版本控制與備份策略,可安全完成大規模項目編碼遷移。

copyright © 萬盛學電腦網 all rights reserved