php实现天气回复
使用 PHP 实现天气回复功能
PHP 可以通过调用天气 API 获取实时天气数据,并生成回复信息。以下是实现方法:
选择天气 API 服务
常见的免费天气 API 包括:
- 和风天气(https://dev.qweather.com/)
- OpenWeatherMap(https://openweathermap.org/api)
- 心知天气(https://www.seniverse.com/)
注册账号并获取 API Key。
安装必要的库
使用 cURL 或 Guzzle HTTP 客户端发送 API 请求:
composer require guzzlehttp/guzzle
获取天气数据
示例代码使用 OpenWeatherMap API:
<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
function getWeather($city) {
$apiKey = 'YOUR_API_KEY';
$client = new Client();
try {
$response = $client->get("http://api.openweathermap.org/data/2.5/weather?q=$city&appid=$apiKey&units=metric");
$data = json_decode($response->getBody(), true);
return [
'temperature' => $data['main']['temp'],
'humidity' => $data['main']['humidity'],
'description' => $data['weather'][0]['description']
];
} catch (Exception $e) {
return null;
}
}
?>
生成天气回复
根据获取的数据生成回复消息:
function generateWeatherReply($city) {
$weather = getWeather($city);
if (!$weather) {
return "无法获取 $city 的天气信息,请检查城市名称或稍后再试。";
}
return "$city 当前天气:\n"
. "温度:{$weather['temperature']}°C\n"
. "湿度:{$weather['humidity']}%\n"
. "天气状况:{$weather['description']}";
}
使用示例
echo generateWeatherReply('Beijing');
输出示例:
Beijing 当前天气:
温度:23°C
湿度:45%
天气状况:晴天
处理中文城市名
如果 API 不支持中文城市名,可以使用拼音或城市 ID:
$cityMap = [
'北京' => 'Beijing',
'上海' => 'Shanghai'
];
$cityName = '北京';
$apiCityName = $cityMap[$cityName] ?? $cityName;
错误处理
增加更完善的错误处理机制:
try {
// API 请求代码
} catch (GuzzleHttp\Exception\ClientException $e) {
// 处理 4xx 错误
} catch (GuzzleHttp\Exception\ServerException $e) {
// 处理 5xx 错误
}
缓存机制
减少 API 调用次数,可以使用文件缓存或 Redis:
function getWeatherWithCache($city, $ttl = 3600) {
$cacheFile = "cache/{$city}.json";
if (file_exists($cacheFile) && time() - filemtime($cacheFile) < $ttl) {
return json_decode(file_get_contents($cacheFile), true);
}
$weather = getWeather($city);
file_put_contents($cacheFile, json_encode($weather));
return $weather;
}
安全考虑
- 验证用户输入,防止 SQL 注入或 XSS 攻击
- 不要在前端暴露 API Key
- 对 API 响应进行验证
以上方法提供了完整的 PHP 天气回复实现方案,可以根据实际需求调整 API 选择和数据展示方式。







