當 PHP 通過 exec()、shell_exec() 等函數調用系統命令時,若命令輸出包含中文,PHP 直接獲取的字符串往往會出現亂碼(如 ?230?180?187...),這是由於編碼不一致導致的:系統終端通常按當前 Locale 輸出(如 GBK),而 PHP 腳本可能按 UTF-8 接收。
在 Shell 命令中管道接 iconv 強制轉換輸出編碼:
<?php
// Windows 系統:將命令輸出從 GBK 轉為 UTF-8
$output = shell_exec('your_command 2>&1 | iconv -f GBK -t UTF-8');
// Linux 系統若已是 UTF-8 可省略,或統一寫法:
$output = shell_exec('your_command 2>&1 | iconv -f GBK -t UTF-8 //IGNORE');
echo $output; // 正常顯示中文
?>
優點: 源頭解決編碼問題,PHP 端無需額外處理,適用於所有輸出場景。
<?php
$raw = shell_exec('your_command 2>&1');
// 檢測編碼並轉換(需安裝 mbstring 或 iconv 擴展)
$output = mb_convert_encoding($raw, 'UTF-8', 'GBK'); // 或 auto
echo $output;
?>
注意: mb_convert_encoding 的第三個參數為來源編碼,若不確定可用 'auto' 讓擴展嘗試檢測,但显式指定更可靠。
原文提供的 shell2txt() 函數針對包含 ? 字符的路徑字符串做了解碼,但邏輯較繁瑣且針對性較窄。現代 PHP 建議採用上述通用方案。
en_US.UTF-8 或 zh_CN.UTF-8,從源頭避免編碼不一致。python3 -X utf8 script.py、java -Dfile.encoding=UTF-8。header('Content-Type: text/html; charset=UTF-8')。2>&1 將 stderr 合併到 stdout,統一管道轉碼。<?php
/**
* 執行 Shell 命令並返回 UTF-8 編碼結果
* @param string $cmd
* @return string
*/
function exec_utf8($cmd) {
// Windows 下命令輸出通常為 GBK,Linux 為 UTF-8
$is_win = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN';
$full_cmd = $cmd . ' 2>&1';
if ($is_win) {
$full_cmd .= ' | iconv -f GBK -t UTF-8 //IGNORE';
}
$output = shell_exec($full_cmd);
return $output ?: '';
}
// 使用示例
echo exec_utf8('dir C:\\Windows'); // Windows
echo exec_utf8('ls /home'); // Linux
?>
採用「命令層面管道轉碼 + PHP 端統一 UTF-8」的雙重保障,可徹底解決 Shell 命令中文輸出亂碼問題,提升跨平台兼容性。