php json_decode返回null
function posturl($gateurl,$data){
$headers = array("Content-type: application/x-www-form-urlencoded", "'charset='utf-8'");
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$gateurl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch ,CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch ,CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$res = curl_exec($ch);
curl_close($ch);
$result = json_decode($res, true);
return $result;
}
上面的代码块http_build_query:使用给出的关联(或下标)数组生成一个经过 URL-encode 的请求字符串,
当传送的value值里面有json_encode时,里面会被http_build_query转成实体,需要再转回来再json_decode;
本文主要为大家讲解了php在使用json_decode函数解码json字符串时,解码不成功返回NULL的问题原因分析和解决方法,感兴趣的同学参考下.
一般来说,php对json字符串解码使用json_decode()函数,第一个参数传字符串,第二个参数若为true,返回array;若为false,返回object。如果返回NULL,说明报错,输出json_last_error(),得到的整数值对应错误提示。如下图所示:

json_last_error()比较常见的是整数4, 是json字符串在json_decode之前已不完整,
用下面的方法可以实现正确解析
$data = stripslashes(html_entity_decode($info)); //$info是传递过来的json字符串
$data = json_decode($data,TRUE);
这时候$data就是解析后的数组了!
html_entity_decode() 函数的作用是把 HTML 实体转换为字符。
stripslashes() 函数的作用是删除反斜杠。
相关推荐
-
PHP8种变量类型的详细讲解2025-02-22 00:32:24
-
php+apache 和 php+nginx的区别2025-02-22 00:21:27
-
PHP:与workerman结合实现定时任务2025-02-22 00:15:57
-
Nginx的Rewrite规则与实例2025-02-22 00:15:39
-
MySql中身份证字段的简单脱敏介绍2025-02-22 00:15:36