开发者

Why doesn't this work?: decoding json into php array

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

The file encodes an array then just echoes it as this (and echo $json outputs this):

{"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}}} 

Now I'm trying to decode it fro开发者_如何学编程m another page like this:

$myarray = json_decode($json, true);

print_r($myarray);

This outputs nothing, no errors, nothing!


Try this instead (you are mixing " and ' [single quotes instead of double quotes on the string]):

$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);

And your result:

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
                )

        )

)


Try wrapping the json string in single quotes instead of double quotes:

$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}}}';


I had no problems executing the following code:

$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);

My guess would be that the file you are trying to read from does not exist. Remember that, if you are using Linux, file names are case-sensitive. Use the file_exists() function to check this:

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜