PHP自5.2版本开始,原生提供了JSON的封包和解包的函数,PHP的JSON操作对JSON的格式要求比较严格。
参考http://www.phpddt.com/php/json_decode-bom.html一文得知:
json_decode要求的字符串比较严格:
(1)使用UTF-8编码
(2)不能在最后元素有逗号
(3)不能使用单引号
(4)不能有\r,\t,如果有请替换
因此,返回NULL的情况还不少,这个得靠大家写代码的时候多多细心。本文要讲的是我从POST获取的JSON格式的字符串,我确保字符串打印出来,看起来没有任何错误,但是json_decode就是返回NULL。这个奇葩的问题,在网上找了很久,有些网友说是字符集的问题,我测试确认后不是,那到底是什么问题呢?
首先,我发送一个webservice请求:
post操作封装函数:
<span style="font-size:14px;">function do_post_request($url, $data, $optional_headers = null)
{
$params = array('http' => array(
'method' => 'POST',
'content' => $data
));
if ($optional_headers !== null) {
$params['http']['header'] = $optional_headers;
}
$ctx = stream_context_create($params);
$fp = @fopen($url, 'rb', false, $ctx);
if (!$fp) {
throw new Exception("Problem with $url, $php_errormsg");
}
$response = @stream_get_contents($fp);
if ($response === false) {
throw new Exception("Problem reading data from $url, $php_errormsg");
}
return $response;
}</span>
(1)发起POST请求:
<span style="font-size:14px;"><span style="font-family:Tahoma;font-size:12px;">$ur