今天遇到一个问题,由于不能用file_get_contents()函数,所以需要用到curl,但是curl以文件流形式返回后,得到的是一个json的html,也就是string格式的,json_decode()后往往得到是null。在这里做一个转换记录:
1.首先php中的json_decode要求的字符串比较严格,以下几点需注意:
(1)使用UTF-8编码
(2)不能在最后元素有逗号
(3)不能使用单引号
(4)不能有\r,\t,如果有请替换。
$jsonArr=json_decode($jsonStr,true) //尝试在json_decode()的第二个参数中添加true.
$jsonStr = preg_replace('/[\x00-\x1F\x80-\x9F]/u', '', trim($jsonStr)); //以去掉其他破坏json字符串的字符
$jsonStr = htmlspecialchars_decode($jsonStr); //可能因为在 json 字符串中反斜杠被转义,只需要用 htmlspecialchars_decode() 函数处理一下
$jsonStr= stripslashes(html_entity_decode($jsonStr); //html_entity_decode() 函数的作用是把 HTML 实体转换为字符。
$jsonArr= json_decode($jsonStr,TRUE);
$jsonArr= json_decode(trim($jsonStr,chr(239).chr(187).chr(191)),true);//交互中出现的问题,不小心在返回的json字符串中返回了BOM头的不可见字符,某些编辑器默认会加上BOM头,如下处理才能正确解析json数据: