$str2='{"code":200,"datas":{"id":1,"coupon_id":"123","validity":"2018-08-14","is_use":0,"source":"2","create_time":"2018-08-14 15:06:40"}}'; var_dump(json_decode($str2)); //輸出為 NULL
json在線解析器去掉兩邊單引號是可以解析的
但是實際代碼運行,不論是直接json_decode()還是去掉兩邊單引號都無法解析.
造成這種問題的源頭就是bom頭,返回的結果是帶bom頭的utf8格式的數據,因此只要去除bom頭就好了,添加一個方法:
function clearBom($str){ $bom = chr(239).chr(187).chr(191); return str_replace($bom ,'',$str); }
然后問題就解決了
$str2='{"code":200,"datas":{"id":1,"coupon_id":"123","validity":"2018-08-14","is_use":0,"source":"2","create_time":"2018-08-14 15:06:40"}}'; var_dump(json_decode(clearBom($str2))); 結果如下: object(stdClass)#1 (2) { ["code"]=> int(200) ["datas"]=> object(stdClass)#2 (6) { ["id"]=> int(1) ["coupon_id"]=> string(3) "123" ["validity"]=> string(10) "2018-08-14" ["is_use"]=> int(0) ["source"]=> string(1) "2" ["create_time"]=> string(19) "2018-08-14 15:06:40" } }