为什么这不起作用?:将json解码为php数组

时间:2011-05-16 18:03:52

标签: php arrays json

$json = file_get_contents('outputsjson.php');

该文件对数组进行编码,然后只是将其回显(并echo $json输出):

{"theList":{"1":{"name":"DSC04156.JPG","title":"DSC04156.JPG","width":3264},"2":{"name":"DSC04157.JPG","title":"DSC04157.JPG","width":3264},"3":{"name":"DSC04158.JPG","title":"DSC04158.JPG","width":3264},"4":{"name":"DSC04159.JPG","title":"DSC04159.JPG","width":3264}}} 

现在我正试图从另一个页面解码它:

$myarray = json_decode($json, true);

print_r($myarray);

这没有输出,没有错误,什么都没有!

3 个答案:

答案 0 :(得分:3)

试试这个(你混合"' [单引号而不是字符串上的双引号]):

$json = '{"theList":{"1":{"name":"DSC04156.JPG","title":"DSC04156.JPG","width":3264},"2":{"name":"DSC04157.JPG","title":"DSC04157.JPG","width":3264},"3":{"name":"DSC04158.JPG","title":"DSC04158.JPG","width":3264},"4":{"name":"DSC04159.JPG","title":"DSC04159.JPG","width":3264}}} ';

$myarray = json_decode($json, true);

print_r($myarray);

你的结果:

Array
(
    [theList] => Array
        (
            [1] => Array
                (
                    [name] => DSC04156.JPG
                    [title] => DSC04156.JPG
                    [width] => 3264
                )

            [2] => Array
                (
                    [name] => DSC04157.JPG
                    [title] => DSC04157.JPG
                    [width] => 3264
                )

            [3] => Array
                (
                    [name] => DSC04158.JPG
                    [title] => DSC04158.JPG
                    [width] => 3264
                )

            [4] => Array
                (
                    [name] => DSC04159.JPG
                    [title] => DSC04159.JPG
                    [width] => 3264
                )

        )

)

答案 1 :(得分:1)

尝试用单引号包装json字符串而不是双引号:

$json = '{"theList":{"1":{"name":"DSC04156.JPG","title":"DSC04156.JPG","width":3264},"2":{"name":"DSC04157.JPG","title":"DSC04157.JPG","width":3264},"3":{"name":"DSC04158.JPG","title":"DSC04158.JPG","width":3264},"4":{"name":"DSC04159.JPG","title":"DSC04159.JPG","width":3264}}}';

答案 2 :(得分:0)

执行以下代码时没有问题:

$json = '{"theList":{"1":{"name":"DSC04156.JPG","title":"DSC04156.JPG","width":3264},"2":{"name":"DSC04157.JPG","title":"DSC04157.JPG","width":3264},"3":{"name":"DSC04158.JPG","title":"DSC04158.JPG","width":3264},"4":{"name":"DSC04159.JPG","title":"DSC04159.JPG","width":3264}}}';
$myarray = json_decode($json, true);
print_r($myarray);

我的猜测是您尝试读取的文件不存在。请记住,如果您使用的是Linux,则文件名区分大小写。使用file_exists()功能检查:

var_dump(file_exists('outputsjson.php'));