[英]Can't decode JSON from file in PHP
我在PHP中遇到json_decode
问题:
我有这个档案:
{1: ['oi','oi'], 2: ['foo','bar']}
这是我的php代码:
<?php
$string = file_get_contents("quizen.json"); // the file
$json = json_decode($string);
echo $json[1][0]
?>
但是回声返回任何东西,我使用了var_dump,并且我得到了NULL! 有什么问题?
问题是您的文件不是有效的JSON,因为它对字符串使用单引号并将整数作为对象键:
{1: ['oi','oi'], 2: ['foo','bar']}
另外,由于JSON是对象,因此您应该使用json_decode($string, true)
将其解码为关联数组。
根据JSON规范 :
值可以是带双引号的字符串,也可以是数字,也可以是true或false或null,或者是对象或数组。
同样,对象键必须是字符串。
如果将单引号更改为双引号,然后编辑PHP的decode_json
调用以解码为关联数组,则它应该可以工作。 例如:
JSON:
{"1": ["oi","oi"], "2": ["foo","bar"]}
PHP:
<?php
$string = file_get_contents("quizen.json"); // the file
$json = json_decode($string, true); // set to true for associative array
echo $json["1"][0];
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.