【发布时间】:2015-10-06 11:02:19
【问题描述】:
我想从OWM API 获取天气数据,在这种情况下我想获取temerature 和discription 信息。我怎么能通过 PHP 从他们的 API 中“拉”这个?
【问题讨论】:
标签: php api weather-api openweathermap
我想从OWM API 获取天气数据,在这种情况下我想获取temerature 和discription 信息。我怎么能通过 PHP 从他们的 API 中“拉”这个?
【问题讨论】:
标签: php api weather-api openweathermap
真的很简单,看看这段代码。
<?php
//get JSON
$json = file_get_contents('http://api.openweathermap.org/data/2.5/find?q=Calabar,NG&type=accurate&mode=json');
//decode JSON to array
$data = json_decode($json,true);
//show data
var_dump($data);
//description
echo $data['weather'][0]['description'];
//temperature
echo $data['main']['temp'];
?>
首先你需要使用function file_get_contents() 获取文件/字符串,在这种情况下它是 JSON 字符串。在您需要使用函数json_decode() 解码此字符串之后。参数 true 表示我们要将此字符串解析为 array 而不是 object。在此操作之后,您可以使用此数据集,因为它是简单的变量类型的数组。就是这样。
编辑:
根据下面的Prodigy评论编辑网址
【讨论】:
URL 改变了一点 http://api.openweathermap.org/data/2.5/weather?q=London 到这样的 http://api.openweathermap.org/data/2.5/find?q=Calabar,NG&type=accurate&mode=json
您可以使用 Curl 或 file_get_contents,然后保存其中任何一个的响应。然后解析您正在寻找的值的响应。
【讨论】: