要传递到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实体(如我看到的
S中存在)
这实际上是怪异的正确的做法是修复如何生成data.json
确保非html编码返回JSON数据,字符集是UTF-8,响应内容类型是Content-Type: application/json
。
我们不能在这里加深这一点,因为我不知道data.json
来自哪里或产生它的代码。最终你可能会发布另一个答案。
所以这里是一个快速修复只要正确的方法是我刚才建议的。
在解码html实体时,非中断空格
变为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 = html_entity_decode(" ");
// remove every occurrence of the character sequence
$decodedstr = str_replace($nbsp, "", $decodedstr);
$jarray = json_decode($decodedstr, true);
你试过了,没有'html_entity_decode'步骤,只是'json_decode($ str,true)'? – rickdenhaan
在'json_decode'方法后面打印'json_last_error()'方法 –
oke我试过没有html_entity_decode,它仍然返回null。当我打印json_last_error我得到4 – FutureCake