我在 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]
?>
但是 echo 返回任何内容,我使用了 var_dump,并且得到 NULL! 有什么问题吗?
最佳答案
问题是您的文件不是有效的 JSON,因为它对字符串使用单引号并使用整数作为对象键:
{1: ['oi','oi'], 2: ['foo','bar']}
此外,由于 JSON 是一个对象,因此您应该使用 json_decode($string, true)
将其解码为关联数组。
根据the JSON spec :
A value can be a string in double quotes, or a number, or true or false or null, or an object or an array.
此外,对象键必须是字符串。
如果您将单引号更改为双引号并编辑 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];
?>
关于php - 无法从 PHP 文件中解码 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30686319/