2017-05-07 55 views
1

我有以下的代码转换JSON到数组:的Json空数组json_decode

$str = file_get_contents('http://localhost/data.json'); 
$decodedstr = html_entity_decode($str); 
$jarray = json_decode($decodedstr, true); 


echo "<pre>"; 
print_r($jarray); 
echo "</pre>"; 

但我$jarray保持返回null ......我不知道为什么会这样。我已经验证了我的JSON在这个问题: validated json question谁能告诉我我做错了什么?或发生了什么。提前致谢。

当我赞同我的$海峡,我得到如下:image of echo of $str

+0

你试过了,没有'html_entity_decode'步骤,只是'json_decode($ str,true)'? – rickdenhaan

+3

在'json_decode'方法后面打印'json_last_error()'方法 –

+0

oke我试过没有html_entity_decode,它仍然返回null。当我打印json_last_error我得到4 – FutureCake

回答

1

要传递到json_decode字符串无效JSON,这是返回NULL的原因。

当我从评论检查错误代码,请产生给4对应于恒JSON_ERROR_SYNTAX只是意味着JSON字符串有语法错误

(见http://php.net/manual/en/function.json-last-error.php


您应检查(回声)您

$str = file_get_contents('http://localhost/data.json'); 

得到什么(你可以编辑你的答案,并张贴 - 或它的一部分)

确定它无效JSON;问题在于:data.json

然后当你修复的东西,并从data.json得到什么预计我会确保你真的需要使用html_entity_decode上获取的数据。

这将是“奇怪的”有HTML编码的JSON数据。


UPDATE

看着你从data.json得到什么它似乎JSON数据实际上包含HTML实体(如我看到的&nbsp; S中存在)

这实际上是怪异的正确的做法是修复如何生成data.json确保非html编码返回JSON数据,字符集是UTF-8,响应内容类型是Content-Type: application/json

我们不能在这里加深这一点,因为我不知道data.json来自哪里或产生它的代码。最终你可能会发布另一个答案。

所以这里是一个快速修复只要正确的方法是我刚才建议的。

在解码html实体时,非中断空格&nbsp;变为2字节的UTF-8字符(字节值196,160),对于JSON编码的数据,其为无效

这个想法是删除这些字符;你的代码变成:

$str = file_get_contents('http://localhost/data.json'); 
$decodedstr = html_entity_decode($str); 

// the character sequence for decoded HTML &nbsp; 
$nbsp = html_entity_decode("&nbsp;"); 

// remove every occurrence of the character sequence 
$decodedstr = str_replace($nbsp, "", $decodedstr); 

$jarray = json_decode($decodedstr, true); 
+0

请参阅我编辑的答案 – FutureCake

+0

@FutureCake更新了答案。 – Paolo

+0

你是真正的MVP它的工作感谢人!现在我明白我在做什么错了,再次感谢:) – FutureCake

0

从PHP手册

http://php.net/manual/en/function.json-decode.php

返回

... NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit

所以,一定传给json_decode()的JSON字符串无效:

也许因为html_entity_decode

+0

所以如果我的json超过了递归限制我该如何解决这个问题?我得到的数据来自客户端。所以我可能不能要求他改变json。 – FutureCake

+0

@FutureCake错误不是由过多的递归引起的,而是由语法错误引起的(请参阅我的回答详情) – Paolo