当前位置:首页 > PHP

php实现天气

2026-01-30 03:57:54PHP

使用第三方天气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>

php实现天气

标签: 天气php
分享给朋友:

相关文章

php实现分页

php实现分页

PHP实现分页的基本方法 使用LIMIT和OFFSET进行数据库查询分页。通过计算当前页码和每页显示数量,动态生成SQL语句。 $page = isset($_GET['page']) ? (in…

php实现socket

php实现socket

PHP 实现 Socket 通信 PHP 可以通过 socket 扩展实现网络通信,支持 TCP/UDP 协议。以下是实现 Socket 通信的核心步骤和代码示例。 创建 TCP 服务器 //…

php长连接实现

php长连接实现

PHP 长连接实现方法 长连接(Keep-Alive)允许客户端与服务器在一次TCP连接中发送和接收多个HTTP请求/响应,减少重复建立连接的开销。以下是PHP中实现长连接的几种方式: 配置HT…

php实现登录

php实现登录

PHP 登录功能实现 数据库连接与用户表创建 创建一个数据库连接文件 db.php,用于管理数据库连接。MySQL 示例代码如下: <?php $host = 'localhost'; $db…

php验证码实现

php验证码实现

验证码实现方法 在PHP中实现验证码功能通常涉及生成随机字符串或数字,将其转换为图像,并通过会话(Session)进行验证。以下是几种常见的实现方式: 使用GD库生成图像验证码 GD库是PHP内置的…

php实现注册

php实现注册

注册功能实现步骤 数据库准备 创建用户表,包含字段如id、username、password、email等。示例SQL: CREATE TABLE users ( id INT AUTO_I…