json_deocde php 举例_使用json_decode在PHP中解析JSON对象

I tried to request the weather from a web service supplying data in JSON format. My PHP request code, which did not succeed was:

$url="http://www.worldweatheronline.com/feed/weather.ashx?q=schruns,austria&format=json&num_of_days=5&key=8f2d1ea151085304102710";

$json = file_get_contents($url);

$data = json_decode($json, TRUE);

echo $data[0]->weather->weatherIconUrl[0]->value;

This is some of the data that was returned. Some of the details have been truncated for brevity, but object integrity is retained:

{ "data":

{ "current_condition":

[ { "cloudcover": "31",

... } ],

"request":

[ { "query": "Schruns, Austria",

"type": "City" } ],

"weather":

[ { "date": "2010-10-27",

"precipMM": "0.0",

"tempMaxC": "3",

"tempMaxF": "38",

"tempMinC": "-13",

"tempMinF": "9",

"weatherCode": "113",

"weatherDesc": [ {"value": "Sunny" } ],

"weatherIconUrl": [ {"value": "http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0001_sunny.png" } ],

"winddir16Point": "N",

"winddirDegree": "356",

"winddirection": "N",

"windspeedKmph": "5",

"windspeedMiles": "3" },

{ "date": "2010-10-28",

... },

... ]

}

}

}

解决方案

This appears to work:

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

print '
';

}

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值