OpenWeatherMap 注册登录,API密钥管理页面并生成一个API密钥就OK了
[Python] 纯文本查看 复制代码 <?php
$apiKey = "YOUR_API_KEY";
$cityId = "CITY_ID"; // 或者使用城市名,如:"London,uk"
$apiUrl = "http://api.openweathermap.org/data/2.5/weather?id={$cityId}&appid={$apiKey}&units=metric";
$curl = curl_init();
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_URL, $apiUrl);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_VERBOSE, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($curl);
curl_close($curl);
$data = json_decode($response);
$currentTime = time();
if($data->cod == 200) {
echo "天气状态:" . $data->weather[0]->description . "\n";
echo "当前温度:" . $data->main->temp . "°C\n";
echo "湿度:" . $data->main->humidity . "%\n";
echo "风速:" . $data->wind->speed . " meter/sec\n";
echo "测量时间:" . date("Y-m-d H:i:s", $currentTime);
} else {
echo "获取天气信息失败!";
}
?>
PHP源码 |