PHP 获取JSON json_decode返回NULL解决办法

json字符串如下 

$json = "{"cmd":"get_terminal_list","state":"1","msg":"","amount":"1"}";

正常情况

$aaa=json_decode($json,true);

echo $aaa['cmd'] = get_terminal_list;

 

特殊情况,如果json字符串中有下列情况,则需要转换一下在json_decode才行

在用json_decode对JSON格式的字符串进行解码时竟然为空,页面空白啊,整半天检查这里检查那里,问同事都没用。

是有BOM头输出,解决办法如下:

1、json_decode要求的字符串比较严格:

(1)使用UTF-8编码
(2)不能在最后元素有逗号
(3)不能使用单引号
(4)不能有\r,\t,如果有请替换
解决办法一:
所以问题来了,不小心在返回的json字符串中返回了BOM头的不可见字符,某些编辑器默认会加上BOM头,如下处理才能正确解析json数据:

<?php
$aaa = json_decode(trim($json,chr(239).chr(187).chr(191)),true);

 

 

方法二:在转为json之前对中文进行转码

转载地址:http://www.cnblogs.com/anns/p/5974143.html

转载地址:https://segmentfault.com/q/1010000002991973

posted on 2025-07-03 17:48  泽一年  阅读(114)  评论(0)    收藏  举报

导航