php实现天气
使用第三方天气API实现
PHP可以通过调用第三方天气API获取天气数据。常见的免费天气API包括OpenWeatherMap、WeatherAPI、和风天气等。以下以OpenWeatherMap为例:
$apiKey = 'your_api_key';
$city = 'Beijing';
$url = "http://api.openweathermap.org/data/2.5/weather?q=$city&appid=$apiKey&units=metric";
$response = file_get_contents($url);
$data = json_decode($response, true);
if ($data['cod'] == 200) {
$temp = $data['main']['temp'];
$humidity = $data['main']['humidity'];
$description = $data['weather'][0]['description'];
echo "当前温度: $temp°C, 湿度: $humidity%, 天气状况: $description";
} else {
echo "获取天气信息失败";
}
使用cURL替代file_get_contents
某些服务器可能禁用file_get_contents函数,可以使用cURL实现:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
缓存天气数据
频繁调用API可能受限制,可以添加缓存机制:
$cacheFile = 'weather_cache.json';
$cacheTime = 3600; // 1小时缓存
if (file_exists($cacheFile) && time() - filemtime($cacheFile) < $cacheTime) {
$data = json_decode(file_get_contents($cacheFile), true);
} else {
$data = json_decode(file_get_contents($url), true);
file_put_contents($cacheFile, json_encode($data));
}
显示天气图标
根据天气状况显示相应图标:
$weatherIcons = [
'clear' => '☀️',
'clouds' => '☁️',
'rain' => '🌧️',
'snow' => '❄️'
];
$icon = $weatherIcons[strtolower($data['weather'][0]['main'])] ?? '🌈';
echo "天气图标: $icon";
处理多城市查询
支持同时查询多个城市天气:
$cities = ['Beijing', 'Shanghai', 'Guangzhou'];
foreach ($cities as $city) {
$url = "http://api.openweathermap.org/data/2.5/weather?q=$city&appid=$apiKey";
// 获取并显示每个城市天气
}
错误处理增强
添加更健壮的错误处理:
try {
$response = file_get_contents($url);
if ($response === false) {
throw new Exception('API请求失败');
}
$data = json_decode($response, true);
// 处理数据...
} catch (Exception $e) {
error_log($e->getMessage());
echo '暂时无法获取天气信息';
}
使用国内天气API
国内开发者可以考虑和风天气或心知天气API:
// 和风天气示例
$url = "https://free-api.heweather.net/s6/weather/now?location=beijing&key=your_key";
前端展示优化
将天气数据以更友好的方式展示:
<div class="weather-card">
<h3><?php echo $data['name']; ?></h3>
<div class="temp"><?php echo $data['main']['temp']; ?>°C</div>
<div class="details">
<span>湿度: <?php echo $data['main']['humidity']; ?>%</span>
<span>风速: <?php echo $data['wind']['speed']; ?>m/s</span>
</div>
</div>






