今天遇到一個問題,json_decode解析json數據返回null,試了各種方法都不行,最后發現,原來是json文件編碼的問題。
當json_decode解析utf-8帶BOM格式的json數據時,會返回null。
json_decode函數能夠接收utf8編碼的參數,但是當參數中包含BOM時,json_decode就會失效。
這個函數能將給定的字符串轉換成UTF-8編碼,移除其中的BOM。
下面是PHP代碼:
function prepareJSON($input) { //This will convert ASCII/ISO-8859-1 to UTF-8. //Be careful with the third parameter (encoding detect list), because //if set wrong, some input encodings will get garbled (including UTF-8!) $imput = mb_convert_encoding($input, 'UTF-8', 'ASCII,UTF-8,ISO-8859-1'); //Remove UTF-8 BOM if present, json_decode() does not like it. if(substr($input, 0, 3) == pack("CCC", 0xEF, 0xBB, 0xBF)) $input = substr($input, 3); return $input; } //Usage: $myFile = file_get_contents('somefile.json'); $myDataArr = json_decode(prepareJSON($myFile), true);
來源於:http://phpcode8.com/?p=555