phpCB 是一款命令列 PHP 程式碼風格美化工具。本文示範如何編寫 PHP 腳本遞迴掃描目錄,批量呼叫 phpCB.exe 格式化所有 PHP 檔案。
<?php
header("Content-type: text/html; charset=gb2312");
define('ROOT_PATH', dirname(__FILE__));
$topath = "ww"; // 目標目錄(相對路徑,不含首尾斜線)
$path = ROOT_PATH . "/" . $topath;
$arr = get_all_files($path);
for ($i = 0; $i < count($arr); $i++) {
$ext = fileext($arr[$i]);
if ($ext == "php") {
$cmd = "phpCB.exe " . $arr[$i] . " > " . $arr[$i] . ".phpCB";
system($cmd);
unlink($arr[$i]);
@rename($arr[$i] . ".phpCB", $arr[$i]);
}
}
function get_all_files($path) {
$list = array();
foreach (glob($path . '/*') as $item) {
if (is_dir($item)) {
$list = array_merge($list, get_all_files($item));
} else {
$list[] = $item;
}
}
return $list;
}
function fileext($filename) {
return trim(substr(strrchr($filename, '.'), 1, 10));
}
?>
phpCB.exe 放入系統 PATH 目錄(如 C:\Windows\System32)。$topath 為目標目錄名。proc_open 替代 system,可捕獲 stderr 進行錯誤處理。--dry-run),先預覽變更再寫入。.gitignore 排除規則,避免格式化第三方庫。此腳本適合快速整理歷史專案風格,長期維護請遷移至標準化工具鏈。