IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    更换天气信源

    dujun发表于 2024-09-11 08:44:00
    love 0

    宝宝日记后台编辑器根据定位自动获取当日天气信息。这项功能开发于 2017 年,当时选定的方案是采集中国天气网页面,通过正则表达式提取相关数据。但现在偶然发现其天气信息与墨迹天气 APP 有差别,我到中国气象局官网验证,与墨迹天气是一致的,也就是说中国天气网数据是错误的。不准确的信源毫无意义,马上决定更换。

    经过对比,最终选定和风天气作为新的天气信源,免费版接口支持每天1000次请求。

    注册

    在官网注册账号(需要邮箱和手机号),创建一个免费订阅,记录 KEY 值。

    调用

    详见文档:https://dev.qweather.com/docs/api/weather/weather-daily-forecast/

    接口调用 PHP 代码参考:

    <?php
    declare(strict_types = 1);
    
    /**
     * 天气 (和风天气)
     */
    class Vendor_Weather
    {
        //获取当日天气
        public static function get(string $location): ?array
        {
            return
                //获取区域信息(LocationID)
                ($locationData = Vendor_Location_Main::format($location))
                && ($raw = Lib_Http::get(sprintf('https://devapi.qweather.com/v7/weather/3d?location=%d&key=%s', $locationData[_C_LOCATION_ID], 上文的 KEY)))
                //返回数据是 JSON 格式并进行了 Gzip 压缩
                && ($ungzip = gzdecode($raw))
                && ($ret = json_decode($ungzip, true))
                && '200' == $ret['code']
                && ($data = $ret['daily'][3] ?? null)
                && date('Y-m-d') === ($data['fxDate'] ?? null) ?
                    [
                        _C_WEATHER             => $data['textDay'] === $data['textNight'] ? $data['textDay'] : $data['textDay'] . '转' . $data['textNight'],
                        _C_MINIMUM_TEMPERATURE => $data['tempMin'],
                        _C_MAXIMUM_TEMPERATURE => $data['tempMax']
                    ] : null;
        }
    }

    其中,LocationID 可以通过另一个接口获取,详见文档:https://dev.qweather.com/docs/api/geoapi/city-lookup/

    不过我是本地实现的,自行整理了一份映射表。[附件]点此下载,仅供参考。



沪ICP备19023445号-2号
友情链接