laravel geolite2通过IP地址获取地理位置信息

getip2仓库地址:http://packagist.p2hp.com/packages/geoip2/geoip2

getip2官网:https://dev.maxmind.com/geoip/geoip2/geolite2

1、准备

1.1、下载库

  • getip2官网下载IP地址库

  • 保存到项目目录

1.2、安装

安装getip2

composer require geoip2/geoip2:~2.0

2.使用

use MaxMind\Db\Reader;

public function index()
{
    $reader = new Reader(public_path('lib/GeoLite2-City.mmdb'));
    try {
        $record = $reader->get('59.58.19.72');
        dd($record);//打印结果如下
        
        //假如要获取时区:
        //$timeZone = $record['location']['time_zone'];
    } catch (Reader\InvalidDatabaseException $e) {
    }
}

//打印结果如下

array:6 [▼
  "city" => array:2 [▼
    "geoname_id" => 1792585
    "names" => array:2 [▼
      "en" => "Fuding"
      "zh-CN" => "福鼎"
    ]
  ]
  "continent" => array:3 [▼
    "code" => "AS"
    "geoname_id" => 6255147
    "names" => array:8 [▼
      "de" => "Asien"
      "en" => "Asia"
      "es" => "Asia"
      "fr" => "Asie"
      "ja" => "アジア"
      "pt-BR" => "Ásia"
      "ru" => "Азия"
      "zh-CN" => "亚洲"
    ]
  ]
  "country" => array:3 [▼
    "geoname_id" => 1814991
    "iso_code" => "CN"
    "names" => array:8 [▼
      "de" => "China"
      "en" => "China"
      "es" => "China"
      "fr" => "Chine"
      "ja" => "中国"
      "pt-BR" => "China"
      "ru" => "Китай"
      "zh-CN" => "中国"
    ]
  ]
  "location" => array:4 [▼
    "accuracy_radius" => 500
    "latitude" => 27.3273
    "longitude" => 120.214
    "time_zone" => "Asia/Shanghai"
  ]
  "registered_country" => array:3 [▼
    "geoname_id" => 1814991
    "iso_code" => "CN"
    "names" => array:8 [▼
      "de" => "China"
      "en" => "China"
      "es" => "China"
      "fr" => "Chine"
      "ja" => "中国"
      "pt-BR" => "China"
      "ru" => "Китай"
      "zh-CN" => "中国"
    ]
  ]
  "subdivisions" => array:1 [▼
    0 => array:3 [▼
      "geoname_id" => 1811017
      "iso_code" => "FJ"
      "names" => array:6 [▶]
    ]
  ]
]
posted @ 2019-08-17 15:31  pine007  阅读(1403)  评论(0编辑  收藏  举报