前端/第三方 API 回傳的 JSON 字符串,json_decode() 永遠返回 null,但手動複製字符串測試卻正常,前端 JS 也能解析。經排查,罪魁禍首是 UTF-8 BOM(Byte Order Mark)頭——三個隱形字節 EF BB BF 混入字符串開頭,導致 PHP 解析器誤判格式。
$response = file_get_contents('https://api.example.com/data');
// 實際內容:\xEF\xBB\xBF{"code":200,"msg":"ok"}
$data = json_decode($response, true); // 返回 null
json_last_error(); // JSON_ERROR_SYNTAX (4)
json_decode 不支援 BOM,視為語法錯誤。if (substr($response, 0, 3) === pack('CCC', 0xEF, 0xBB, 0xBF)) {
$response = substr($response, 3);
}
$data = json_decode($response, true); // 正常解析
pack('CCC', 0xEF, 0xBB, 0xBF) 生成二進制 BOM 字節序列,substr 比對並切除。
function removeBom($str) {
if (0 === strpos($str, "\xEF\xBB\xBF")) {
return substr($str, 3);
}
return $str;
}
// 使用
$data = json_decode(removeBom($response), true);
header('Content-Type: application/json; charset=utf-8') 且輸出前無任何輸出)。BOM 是 PHP 開發者的「老朋友」,除 JSON 解析外,也會導致 session_start() 失效、header() 已發送錯誤等疑難雜症。養成「輸入端統一清洗」習慣,能省去無數排查小時。