与GeoIp2的Symfony

时间:2015-08-05 13:38:43

标签: php symfony service doctrine-orm

HelloI需要找到ip的城市,我安装maxmind / GeoIP2-php并下载文件GeoLite2-City.mmdb 31mb GeoLite2-City.mmdb 2,2mb并创建服务AdditionalFunction和函数getInfoIpCity,getInfoIpCountry以及开发人员注册时我使用这个功能如下:

$ip = $request->getClientIp();
$record = $hAid->getInfoIpCountry($ip);
$get_record = $hAid->getInfoIpCity($ip);
$record_coutry = $record->country->name;

我下载GeoLite2-City-CSV_20150707 /和此文件GeoLite2-City-Blocks-IPv4.csv 135.3 mb,在此文件中我找到176.241.128.0/20,690791,690791,0,0,50.4500,30.5233如果我有这个文件怎么能找到名字城市?如果我在变量50.4500,30.5233和谷歌知道这是基辅我怎么得到名称城市? 和服务:

class AdditionalFunction
{
private $rootDir;

public function setRootDir($rootDir)
{
    $this->rootDir = $rootDir;
}

public function getInfoIpCountry($ip)
{
    try {
       $reader = new Reader($this->rootDir.'/data/GeoLite2-Country.mmdb');
       $data = $reader->country($ip);
    } catch (\Exception $e) {
        $data = null;
    }

    return $data;
}

public function getInfoIpCity($ip)
{
    try {
       $reader = new Reader($this->rootDir.'/data/GeoLite2-City.mmdb');
       $data = $reader->city($ip);
        $m = $data->country->name;
        $t = $data->country->isoCode;
        $b = $data->mostSpecificSubdivision->name;
        $c = $data->city->name;
    } catch (\Exception $e) {
        $data = null;
    }

    return $data;
}
}

coutry找对了 但在转储中我有$ c = null,$ b = null 为什么????我需要城市

1 个答案:

答案 0 :(得分:0)

我解决了我的问题我使用maxmind的免费基础但是如果在这个数据库中找不到城市我使用googlr aip并找到latitude&经度,这段代码:

    public function getInfoIpCity($ip)
{
    try {
       $reader = new Reader($this->rootDir.'/data/GeoLite2-City.mmdb');
       $data_geo = $reader->city($ip);

        $name = $data_geo->country->name;
        $isoCode = $data_geo->country->isoCode;
        $mostSpecificSubdivision = $data_geo->mostSpecificSubdivision->name;
        $data = $city = $data_geo->city->name;
        $postal = $data_geo->postal->code; // '55455'
        $latitude = $data_geo->location->latitude; // 50.45
        $longitude = $data_geo->location->longitude;// 30.5233

        if (is_null($data)){
            $url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.$latitude.','.$longitude.'&sensor=false';

            $data = @file_get_contents($url);
            $jsondata = json_decode($data,true);

            if(is_array($jsondata )&& $jsondata ['status'] == "OK")
            {
                $addr = $jsondata ['results'][0]['address_components'][4]['long_name'];
                $addr2 = $jsondata ['results'][0]['address_components'][4]['short_name'];
                $addr3 = $jsondata ['results'][0]['address_components'][3]['long_name'];
            }
            $info = "Country: " . $addr . " | Region: " . $addr2 . " | City: " . $addr3;
            $data = $addr3;

        }

    } catch (\Exception $e) {
        $data = null;
    }

    return $data;
}