调用webservice后json_decode返回NULL [英] json_decode returns NULL after webservice call
问题描述
json_encode
和json_decode
有一个奇怪的行为,我找不到解决方案:
There is a strange behaviour with json_encode
and json_decode
and I can't find a solution:
我的php应用程序调用了php Web服务. Web服务返回的json如下所示:
My php application calls a php web service. The webservice returns json that looks like this:
var_dump($foo):
string(62) "{"action":"set","user":"123123123123","status":"OK"}"
现在我想在应用程序中解码json:
now I like to decode the json in my application:
$data = json_decode($foo, true)
,但它返回NULL
:
var_dump($data):
NULL
我使用php5.
来自Web服务的响应的Content-Type:"text/html; charset=utf-8"
(也尝试使用"application/json; charset=utf-8"
)
I use php5.
The Content-Type of the response from the webservice: "text/html; charset=utf-8"
(also tried to use "application/json; charset=utf-8"
)
可能是什么原因?
推荐答案
只是对OP提供的字符串做了一些快速检查.花括号前的小字符"是 UTF-8 B(yte)O(rder )M(ark) 0xEF 0xBB 0xBF
.我不知道为什么这个字节序列在这里显示为
.
Just did some quick inspection of the string provided by the OP. The small "character" in front of the curly brace is a UTF-8 B(yte) O(rder) M(ark) 0xEF 0xBB 0xBF
. I don't know why this byte sequence is displayed as
here.
从本质上来说,您是从中获取数据的系统发送以UTF-8编码的数据,并在数据之前添加了BOM.您应该先将字符串的前三个字节删除,然后再将其放入json_decode()
(substr($string, 3)
可以).
Essentially the system you aquire the data from sends it encoded in UTF-8 with a BOM preceding the data. You should remove the first three bytes from the string before you throw it into json_decode()
(a substr($string, 3)
will do).
string(62) "{"action":"set","user":"123123123123","status":"OK"}"
^
|
This is the UTF-8 BOM
Kuroki Kaze 被发现,此字符肯定是json_decode
失败.给定格式的字符串不是JSON格式的正确结构(请参见 RFC 4627 )
As Kuroki Kaze discovered, this character surely is the reason why json_decode
fails. The string in its given form is not correctly a JSON formated structure (see RFC 4627)
这篇关于调用webservice后json_decode返回NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!