json_decode 在 webservice 调用后返回 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.来自网络服务的响应的 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)
这篇关于json_decode 在 webservice 调用后返回 NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!