当前位置:首页 > 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";

前端展示优化

将天气数据以更友好的方式展示:

php实现天气

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

php购物车实现

php购物车实现

PHP购物车实现方法 使用PHP实现购物车功能可以通过多种方式完成,以下是几种常见的实现方法: Session存储购物车数据 利用PHP的$_SESSION超全局变量存储购物车数据是最简单的方法。用…

php实现聊天

php实现聊天

实现 PHP 聊天功能的方法 使用 WebSocket 和 PHP 实现实时聊天 WebSocket 是一种全双工通信协议,适合实现实时聊天功能。PHP 可以通过 Ratchet 库实现 WebSo…

php怎么实现登录功能

php怎么实现登录功能

数据库准备 创建用户表存储登录信息,通常包括用户名、密码(需加密)等字段。示例SQL: CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY…

php实现定时

php实现定时

PHP 实现定时任务的方法 PHP 本身是脚本语言,通常需要借助外部工具或框架实现定时任务。以下是几种常见方法: 使用 Cron 任务 Linux 系统自带的 Cron 是常用的定时任务工具。通过编…

php 实现无限分类

php 实现无限分类

无限分类的实现方法 无限分类通常用于构建多层级结构的数据,如商品分类、菜单管理等。以下是几种常见的实现方式: 邻接列表模型(Adjacency List) 这是最简单的实现方式,每个分类记录存储其父…