我试图通过提供JSON
格式数据的Web服务请求天气.我的PHP请求代码没有成功,是:
$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;
Run Code Online (Sandbox Code Playgroud)
这是返回的一些数据.为简洁起见,部分细节已被截断,但保留了对象完整性:
{ "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",
... },
... ]
}
}
}
Run Code Online (Sandbox Code Playgroud)
Max*_*Max 62
这似乎有效:
$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>';
}
Run Code Online (Sandbox Code Playgroud)
如果将json_decode的第二个参数设置为true,则会得到一个数组,因此您无法使用 - >语法.我还建议您安装JSONview Firefox扩展,这样您就可以在一个很好的格式化树视图中查看生成的json文档,类似于 Firefox显示XML结构的方式.这使事情变得容易多了.
小智 49
如果您使用以下代码:
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
Run Code Online (Sandbox Code Playgroud)
TRUE返回一个数组而不是一个对象.
zod*_*zod 22
试试这个例子
$json = '{"foo-bar": 12345}';
$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345
Run Code Online (Sandbox Code Playgroud)
http://php.net/manual/en/function.json-decode.php
NB - 两个负面因素是积极的.:)
归档时间: |
|
查看次数: |
218652 次 |
最近记录: |