PbootCMS开发一个天气预报插件:调用第三方API获取并展示天气数据
本文由广东鲸弘科技有限公司提供惠州小程序开发 / 网站建设专业分享。
本文将开发一个完整的PbootCMS天气预报插件,核心实现「调用第三方免费天气API获取数据+注册自定义模板标签+前端灵活展示」,支持城市切换、自动定位,无需修改系统核心代码,放入对应目录即可安装启用,适配PbootCMS V3.0及以上所有稳定版本。
一、插件核心功能与效果
核心功能:调用免费天气API,获取实时天气数据(温度、天气状况、风向、湿度、气压等);
使用方式:后台启用插件后,前端模板直接使用
{weather}标签展示天气,支持传入城市参数(如{weather city="北京"});额外支持:自动定位当前城市(基于IP)、手动切换城市、数据缓存(减少API调用次数,提升访问速度);
安装便捷:插件结构简洁,无需额外依赖,放入系统插件目录即可完成安装。
二、准备工作(必做)
2.1 选择免费天气API(无需申请KEY,开箱即用)
本插件选用「高德开放平台 公开天气接口」,无需申请API KEY,直接调用即可,适合新手快速开发;若需更高稳定性,可替换为和风天气、彩云天气等(后续会提供替换方法)。
核心API接口(免费公开):
// 根据城市名获取天气(示例:北京) https://restapi.amap.com/v3/weather/weatherInfo?city=110100&key=61232f297a57a5a743894a0e4a801fc3 // 根据IP定位城市,再获取天气(自动定位) https://restapi.amap.com/v3/ip?key=61232f297a57a5a743894a0e4a801fc3
说明:上述API中的key为公开测试key,若出现调用失败,可自行前往高德开放平台申请免费key(注册后即可获取,完全免费)。
2.2 插件目录规范
PbootCMS插件必须放置在 /apps/plugin/ 目录下,单个插件为独立文件夹,命名遵循「小写字母+下划线」规则,本插件目录命名为 weather,最终目录结构如下(最小可用,无需额外扩展):
/apps/plugin/ └── weather/ # 插件主目录(命名:weather,小写无特殊字符) ├── info.json # 插件配置文件(必填,系统识别插件的核心) └── Plugin.php # 插件核心类(必填,实现API调用、标签注册等逻辑)
2.3 注意事项(关键)
确保服务器支持PHP curl扩展(用于调用第三方API),若未开启,需在php.ini中开启curl扩展;
API调用有频率限制(免费接口通常每秒1-2次),插件已添加数据缓存(缓存时间10分钟),避免触发接口限制;
若公开key失效,需及时替换为自己申请的API key,否则无法获取天气数据;
插件仅依赖PbootCMS系统核心,无需额外安装其他插件或扩展,确保系统版本为V3.0及以上。
三、完整插件代码(直接复制使用)
3.1 info.json(插件配置文件)
作用:向PbootCMS系统声明插件信息,确保系统能识别插件,直接复制以下代码,无需修改(可修改作者、描述等无关信息):
{
"name": "weather",
"title": "天气预报插件",
"description": "调用第三方免费天气API,获取实时天气数据,支持{weather}模板标签直接展示,支持城市切换和自动定位",
"author": "开发者名称",
"version": "1.0.0",
"cms_version": "3.0+",
"status": 0,
"depend": [],
"menu": []
}说明:status设为0(默认禁用),安装后需在后台手动启用,避免插件未测试就自动运行。
3.2 Plugin.php(插件核心类)
核心逻辑:注册自定义标签 {weather}、调用天气API、处理数据缓存、格式化天气数据、生成前端展示HTML,直接复制以下代码,可直接使用:
<?php
// 命名空间:必须与插件目录名一致(weather)
namespace apppluginweather;
// 引入系统插件基类(必引,否则无法继承)
use pbootpluginsControllerPlugin;
// 引入系统缓存类(用于缓存天气数据,减少API调用)
use thinkCache;
// 引入系统请求类(用于调用API)
use thinkRequest;
class Plugin extends ControllerPlugin
{
// 插件初始化:注册自定义标签
public function __construct()
{
parent::__construct(); // 必须调用父类构造方法,完成系统初始化
// 注册自定义标签:标签名=weather,回调方法=weatherTag
// 前端使用 {weather} 即可调用,支持传入city参数(如{weather city="上海"})
$this->addMethod('weather', 'weatherTag');
}
/**
* 天气预报标签回调方法(核心逻辑)
* @param array $params 标签传入的参数(如city="北京")
* @param string $content 标签内部内容(本插件无需使用)
* @return string 天气展示的HTML内容
*/
public function weatherTag($params, $content)
{
// 1. 处理传入参数:获取用户指定的城市,无指定则自动定位
$cityName = isset($params['city']) ? trim($params['city']) : $this->getCityByIp();
// 2. 检查缓存:若缓存中有该城市的天气数据(10分钟内),直接使用缓存,无需调用API
$cacheKey = 'weather_data_' . md5($cityName); // 缓存key,避免重复
$weatherData = Cache::get($cacheKey);
// 3. 若缓存中无数据,调用API获取天气
if (!$weatherData) {
$weatherData = $this->getWeatherByCity($cityName);
// 存入缓存,有效期10分钟(600秒),减少API调用次数
Cache::set($cacheKey, $weatherData, 600);
}
// 4. 格式化天气数据,生成前端展示的HTML
return $this->formatWeatherHtml($weatherData, $cityName);
}
/**
* 根据IP自动定位城市(调用高德IP定位API)
* @return string 城市名称(如:北京、上海)
*/
private function getCityByIp()
{
// 高德IP定位API(公开key,可替换为自己的)
$ipApi = 'https://restapi.amap.com/v3/ip?key=61232f297a57a5a743894a0e4a801fc3';
// 调用API(使用curl)
$ipResponse = $this->curlRequest($ipApi);
$ipData = json_decode($ipResponse, true);
// 处理定位结果,默认返回北京(若定位失败)
if ($ipData['status'] == 1 && !empty($ipData['city'])) {
return $ipData['city'];
} else {
return '北京';
}
}
/**
* 根据城市名称获取天气数据(调用高德天气API)
* @param string $cityName 城市名称(如:北京)
* @return array 天气数据数组
*/
private function getWeatherByCity($cityName)
{
// 1. 根据城市名称获取城市编码(高德API需要城市编码,而非直接用城市名)
$cityCode = $this->getCityCode($cityName);
if (!$cityCode) {
// 若城市编码获取失败,返回默认天气数据(北京)
$cityCode = '110100'; // 北京城市编码
}
// 2. 调用高德天气API,获取实时天气
$weatherApi = "https://restapi.amap.com/v3/weather/weatherInfo?city={$cityCode}&key=61232f297a57a5a743894a0e4a801fc3";
$weatherResponse = $this->curlRequest($weatherApi);
$weatherData = json_decode($weatherResponse, true);
// 3. 处理天气数据,返回核心信息(过滤无用数据)
if ($weatherData['status'] == 1 && !empty($weatherData['lives'][0])) {
return $weatherData['lives'][0]; // 实时天气数据
} else {
// 若API调用失败,返回模拟数据,避免前端显示异常
return [
'temperature' => '25',
'weather' => '晴',
'winddirection' => '东风',
'windpower' => '3级',
'humidity' => '50%',
'reporttime' => date('Y-m-d H:i')
];
}
}
/**
* 根据城市名称获取城市编码(高德API辅助接口)
* @param string $cityName 城市名称
* @return string 城市编码(如:110100=北京)
*/
private function getCityCode($cityName)
{
// 高德城市编码查询API(公开key)
$cityApi = "https://restapi.amap.com/v3/config/district?keywords={$cityName}&subdistrict=0&key=61232f297a57a5a743894a0e4a801fc3";
$cityResponse = $this->curlRequest($cityApi);
$cityData = json_decode($cityResponse, true);
if ($cityData['status'] == 1 && !empty($cityData['districts'][0]['adcode'])) {
return $cityData['districts'][0]['adcode'];
} else {
return '';
}
}
/**
* CURL请求工具(用于调用第三方API)
* @param string $url API接口地址
* @return string API返回的响应内容
*/
private function curlRequest($url)
{
// 检查服务器是否支持curl
if (!function_exists('curl_init')) {
return json_encode(['status' => 0, 'msg' => '服务器未开启curl扩展,无法获取天气数据']);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 不直接输出响应内容
curl_setopt($ch, CURLOPT_TIMEOUT, 10); // 超时时间10秒,避免卡死
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 关闭SSL验证(避免https请求失败)
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
/**
* 格式化天气数据,生成前端展示的HTML(可自定义样式)
* @param array $weatherData 天气数据数组
* @param string $cityName 城市名称
* @return string HTML内容
*/
private function formatWeatherHtml($weatherData, $cityName)
{
// 自定义天气图标(根据天气状况匹配,可自行替换为图片图标)
$weatherIcon = $this->getWeatherIcon($weatherData['weather']);
// 生成HTML,样式可根据自己的网站风格修改(内联样式,避免与网站样式冲突)
$html = '<div class="weather-plugin" style="display: flex; align-items: center; gap: 15px; padding: 10px 15px; border-radius: 8px; background: #f5fafe; border: 1px solid #e8f4f8;">';
$html .= '<div class="weather-icon" style="font-size: 36px; color: #4299e1;">' . $weatherIcon . '</div>';
$html .= '<div class="weather-info" style="flex: 1;">';
$html .= '<div class="weather-city" style="font-size: 16px; font-weight: 600; color: #2d3748; margin-bottom: 4px;">' . $cityName . '</div>';
$html .= '<div class="weather-detail" style="font-size: 14px; color: #4a5568; line-height: 1.5;">';
$html .= '温度:' . $weatherData['temperature'] . '℃ | ';
$html .= '天气:' . $weatherData['weather'] . ' | ';
$html .= '风向:' . $weatherData['winddirection'] . $weatherData['windpower'] . ' | ';
$html .= '湿度:' . $weatherData['humidity'] . ' | ';
$html .= '更新时间:' . $weatherData['reporttime'];
$html .= '</div></div></div>';
return $html;
}
/**
* 根据天气状况匹配图标(使用Unicode图标,无需图片)
* @param string $weather 天气状况(如:晴、雨、阴)
* @return string Unicode图标
*/
private function getWeatherIcon($weather)
{
$iconMap = [
'晴' => '☀️',
'多云' => '⛅',
'阴' => '☁️',
'雨' => '
-
pbootcms模板幻灯片调用代码大全
2025-09-01
86 -
Pbootcms留言“提交成功”的默认提示语修改
2025-08-20
145 -
pbootcms网站标签pboot:list当前文档高亮设置教程
2025-08-29
80 -
pbootcms模板首页循环调用所有栏目和对应内容
2025-09-01
95 -
PbootCMS API接口功能开发实操教程
2026-04-20
30 -
pbootcms后台的百度普通收录token怎么填写?怎么获得?
2025-08-19
318 -
Pbootcms字段为空调用另一个字段标签代码
2025-08-20
84 -
PBOOTCMS如何嵌入PDF在线预览功能(手机端如何在线预览PDF文件)
2025-09-02
97 -
pbootcms如何实现留言内容自动发送到QQ邮箱
2025-09-08
83 -
pbootcms列表如何置顶文章,istop不管用怎么办?
2025-08-20
81
咨询热线:
联系电话
联系邮箱
联系QQ
方案获取
