正文
PHP 获取JSON json_decode返回NULL解决办法
小程序:扫一扫查出行
【扫一扫了解最新限行尾号】
复制小程序
【扫一扫了解最新限行尾号】
复制小程序
在用json_decode对JSON格式的字符串进行解码时竟然为空,页面空白啊,整半天检查这里检查那里,问同事都没用。
今天必应搜索了下,问题解决了,原来是有BOM头输出,大虾的解决办法如下:
1)、json_decode($json,boolean):$json为json格式的字符,第二个参数为TRUE时表示转换为数组,默认的FALSE表示
转换为对象。
2)、json_decode要求的字符串比较严格:
(1)使用UTF-8编码
(2)不能在最后元素有逗号
(3)不能使用单引号
(4)不能有\r,\t,如果有请替换
解决办法一:
所以问题来了,不小心在返回的json字符串中返回了BOM头的不可见字符,某些编辑器默认会加上BOM头,如下处理才能正确解析json数据:
<?php
$info = json_decode(trim($info,chr(239).chr(187).chr(191)),true);方法二:在转为json之前对中文进行转码
function arrayRecursive(&$array, $function, $apply_to_keys_also = false)
{
static $recursive_counter = 0;
if (++$recursive_counter >1000 ) {
die('possible deep recursion attack');
}
foreach ($array as $key => $value) {
if (is_array($value)) {
arrayRecursive($array[$key], $function, $apply_to_keys_also);
} else {
$array[$key] = $function($value);
}
if ($apply_to_keys_also && is_string($key)) {
$new_key = $function($key);
if ($new_key != $key) {
$array[$new_key] = $array[$key];
unset($array[$key]);
}
}
}
$recursive_counter--;
}
/**************************************************************
*
* 将数组转换为JSON字符串(兼容中文)
* @param array $array 要转换的数组
* @return string 转换得到的json字符串
* @access public
*
*************************************************************/
function JSON($array)
{
arrayRecursive($array, 'urlencode', true);
$json = json_encode($array);
return urldecode($json);
}
echo JSON($user);
转载地址:https://segmentfault.com/q/1010000002991973
还有一篇介绍的也详细:http://www.cnblogs.com/xcxc/p/3729207.html