且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 json_decode 在 PHP 中解析 JSON 对象

更新时间:2023-12-04 14:37:29

这似乎有效:

$url = 'http://www.worldweatheronline.com/feed/weather.ashx?q=schruns,austria&format=json&num_of_days=5&key=8f2d1ea151085304102710%22';
$content = file_get_contents($url);
$json = json_decode($content, true);

foreach($json['data']['weather'] as $item) {
    print $item['date'];
    print ' - ';
    print $item['weatherDesc'][0]['value'];
    print ' - ';
    print '<img src="' . $item['weatherIconUrl'][0]['value'] . '" border="0" alt="" />';
    print '<br>';
}

如果将 json_decode 的第二个参数设置为 true,则会得到一个数组,因此不能使用 -> 语法.我还建议您安装 JSONview Firefox 扩展,因此您可以在类似于 Firefox 显示 XML 结构的格式良好的树视图中查看生成的 json 文档.这让事情变得容易多了.

If you set the second parameter of json_decode to true, you get an array, so you cant use the -> syntax. I would also suggest you install the JSONview Firefox extension, so you can view generated json documents in a nice formatted tree view similiar to how Firefox displays XML structures. This makes things a lot easier.