符合在yii2框架中使用geoip的扩展

在main.php中
'ip2location' => [
            'class' => '\client\components\IP2Location\Geolocation',
            'database' => '/data/www/html/httpserver/vendor/ip2location/ip2location-php/databases/IP2LOCATION-LITE-DB1.BIN',
            'mode' => 'FILE_IO',
        ],

实现的代码如下

    /**
     * 根据ip获取地理信息
     * @param  [type] $ip       [需要解析的ip]
     * @param  string $language [返回的地理信息的显示语言  可选 [en zh-CN]]
     * @return [type]           [description]
     */
    public static function getLocationByIp($ip, $language = 'zh-CN')
    {
        $reader = new Reader('/data/www/html/httpserver/data/geoIp/GeoLite2-City.mmdb');
        if (empty($ip) || $ip == '127.0.0.1') {
            return [];
        }
        $citys = $reader->city($ip);
        $country = !empty($citys->country->names) ? $citys->country->names : [];
        $subdivisions = !empty($citys->subdivisions) ? $citys->subdivisions[0]->names : [];
        $city = !empty($citys->city->names) ? $citys->city->names : [];
        $data = [
            'country' => isset($country[$language]) ? $country[$language] : array_shift($country),
            'subdivisions' => isset($subdivisions[$language]) ? $subdivisions[$language] : array_shift($subdivisions),
            'city' => isset($city[$language]) ? $city[$language] : array_shift($city),
        ];
        return $data;
    }

你可能感兴趣的:(Yii,PHP)