如何利用API接口获取IP地址及城市地理位置和当地天气状况制作网站问候语

看到别人网站上的装饰品,自己也想要!但是别人没有提供方法啊,于是自己就开始琢磨了,终于大成,特此记录!
在这里插入图片描述
步骤一

获取高德地图开发者key,高德地图API提供了丰富的地理数据服务,其中免费额度为 每月150,000次 调用,日配额为5000次,对于个人开发者而言,这些配额是完全足够的。创建一个weather-api.php将下列代码放入主题根目录,将KEY放入下文private $key = ‘KKKKKKKKEY’; // 高德地图开发者key,

<?php


header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET');
header('Content-Type: application/json;charset=utf-8');

// 高德地图开发者:https://lbs.amap.com/
class WeatherAPI
{
    private $key = 'KKKKKKKKEY'; // 高德地图开发者key
    private $ip;
    private $adcode;
    private $city;
    private $province;
    private $weather = [];

    /**
     * 获取中文星期几
     */
    public function getChineseDayOfWeek()
    {
        $englishDayOfWeek = date('l');
        
        $daysMap = [
            'Monday' => '星期一',
            'Tuesday' => '星期二',
            'Wednesday' => '星期三',
            'Thursday' => '星期四',
            'Friday' => '星期五',
            'Saturday' => '星期六',
            'Sunday' => '星期日'
        ];

        return $daysMap[$englishDayOfWeek];
    }

    /**
     * 获取IP及城市代码
     */
    public function getAddress()
    {
        $this->ip = $this->getIP(); 
        $url = "http://restapi.amap.com/v3/ip?key=" . $this->key . "&ip=" . $this->ip;
        $UserAgent = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506; .NET CLR 3.5.21022; .NET CLR 1.0.3705; .NET CLR 1.1.4322)';
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_ENCODING, '');
        curl_setopt($curl, CURLOPT_USERAGENT, $UserAgent);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        $data = curl_exec($curl);
        curl_close($curl);
        $data = json_decode($data, true);

        $this->province = isset($data['province']) ? $data['province'] : "未知"; // 省份
        $this->city = isset($data['city']) ? $data['city'] : "未知"; // 城市
        $this->adcode = isset($data['adcode']) ? $data['adcode'] : ""; // 城市代码

        if ($this->adcode) {
            $this->getWeather();
        }
        return $this;
    }

    /**
     * 获取天气信息
     */
    public function getWeather()
    {
        // 获取天气信息
        $tqurl = "http://restapi.amap.com/v3/weather/weatherInfo?key=" . $this->key . "&city=" . $this->adcode;
        $UserAgent = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506; .NET CLR 3.5.21022; .NET CLR 1.0.3705; .NET CLR 1.1.4322)';
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $tqurl);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_ENCODING, '');
        curl_setopt($curl, CURLOPT_USERAGENT, $UserAgent);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        $weatherinfo = curl_exec($curl);
        curl_close($curl);
        $weatherinfo = json_decode($weatherinfo, true);

        if (isset($weatherinfo['lives'][0])) {
            $this->weather['weather'] = $weatherinfo['lives'][0]['weather']; // 天气
            $this->weather['temp'] = $weatherinfo['lives'][0]['temperature']; // 温度
            $this->weather['humidity'] = $weatherinfo['lives'][0]['humidity']; // 湿度
            $this->weather['winddirection'] = $weatherinfo['lives'][0]['winddirection']; // 风向
            $this->weather['windpower'] = $weatherinfo['lives'][0]['windpower']; // 风力级别
            $this->weather['reporttime'] = $weatherinfo['lives'][0]['reporttime']; // 更新时间
        }
        return $this;
    }

    /**
     * 获取客户端IP
     */
    function getIP()
    {
        static $realip;
    if (isset($_SERVER)){
        if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])){
            $realip = $_SERVER["HTTP_X_FORWARDED_FOR"];
        } else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
            $realip = $_SERVER["HTTP_CLIENT_IP"];
        } else {
            $realip = $_SERVER["REMOTE_ADDR"];
        }
    } else {
        if (getenv("HTTP_X_FORWARDED_FOR")){
            $realip = getenv("HTTP_X_FORWARDED_FOR");
        } else if (getenv("HTTP_CLIENT_IP")) {
            $realip = getenv("HTTP_CLIENT_IP");
        } else {
            $realip = getenv("REMOTE_ADDR");
        }
    }
    return $realip;
}

    /**
     * 返回天气信息
     */
    public function getResponse($type)
    {
        $day_of_week = $this->getChineseDayOfWeek(); 

        if (!empty($this->weather)) {
            if ($type === 'json') {
                return [
                    'code' => 200,
                    'message' => '获取信息成功',
                    'data' => [
                        'ip' => $this->ip,
                        'province' => $this->province, // 省份
                        'city' => $this->city, // 城市
                        'day_of_week' => $day_of_week, // 星期几
                        'weather' => $this->weather
                    ]
                ];
            } else {
                $current_date = date('Y年m月d日');
                return "来自{$this->city}的朋友,今天是{$current_date},{$day_of_week},天气{$this->weather['weather']},温度{$this->weather['temp']}度,湿度{$this->weather['humidity']}%。祝您有美好的一天!";
            }
        } else {
            return [
                'code' => 500,
                'message' => '无法获取信息',
            ];
        }
    }
}


$weatherAPI = new WeatherAPI();
$weatherAPI->getAddress();

$type = isset($_GET['type']) ? $_GET['type'] : 'json';
$response = $weatherAPI->getResponse($type);

if ($type === 'json') {
    echo json_encode($response, JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} else {
    echo $response;
}
?>

步骤二

开始调用,改成你自己的

 // 使用 AJAX 请求获取天气信息  
        fetch('https://您的网站地址/wp-content/themes/your-theme/weather-api.php?type=json') ```

原文链接

https://www.zddown.icu/1037.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值