php实现天气
使用PHP获取天气数据
通过PHP获取天气数据通常需要调用第三方天气API。以下是几种常见的方法:
方法一:使用OpenWeatherMap API
注册OpenWeatherMap账号并获取API密钥。使用PHP的file_get_contents或cURL请求数据。
$apiKey = '你的API密钥';
$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) {
echo "当前温度: " . $data['main']['temp'] . "°C";
echo "天气状况: " . $data['weather'][0]['description'];
}
方法二:使用心知天气API

心知天气提供中文天气数据服务,适合国内项目。
$apiKey = '你的API密钥';
$city = '北京';
$url = "https://api.seniverse.com/v3/weather/now.json?key=$apiKey&location=$city&language=zh-Hans";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);
if (isset($data['results'])) {
echo "当前温度: " . $data['results'][0]['now']['temperature'] . "°C";
echo "天气状况: " . $data['results'][0]['now']['text'];
}
方法三:使用和风天气API
和风天气提供丰富的天气数据,包括预报和实时天气。

$apiKey = '你的API密钥';
$city = '101010100'; // 城市ID
$url = "https://devapi.qweather.com/v7/weather/now?location=$city&key=$apiKey";
$response = file_get_contents($url);
$data = json_decode($response, true);
if ($data && $data['code'] == '200') {
echo "当前温度: " . $data['now']['temp'] . "°C";
echo "体感温度: " . $data['now']['feelsLike'] . "°C";
}
前端展示天气数据
将获取的天气数据通过HTML和CSS展示给用户。
<div class="weather-card">
<h3><?php echo $city; ?>天气</h3>
<div class="temp"><?php echo $temp; ?>°C</div>
<div class="condition"><?php echo $condition; ?></div>
</div>
<style>
.weather-card {
border: 1px solid #ddd;
padding: 20px;
border-radius: 8px;
width: 200px;
text-align: center;
}
.temp {
font-size: 24px;
font-weight: bold;
}
.condition {
color: #666;
}
</style>
缓存天气数据
为避免频繁调用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 = fetchWeatherData(); // 调用上述API获取数据
file_put_contents($cacheFile, json_encode($data));
}
错误处理
添加错误处理机制,确保API请求失败时用户体验不受影响。
try {
$response = file_get_contents($url);
if ($response === false) {
throw new Exception("无法获取天气数据");
}
$data = json_decode($response, true);
if (!$data) {
throw new Exception("天气数据解析失败");
}
} catch (Exception $e) {
echo "天气服务暂时不可用: " . $e->getMessage();
// 可以显示缓存的旧数据或默认信息
}
通过以上方法,可以在PHP中实现天气数据的获取和展示。选择适合的天气API并根据需求进行定制开发。






