如何从 GeoLite2 获取 isoCode?

How to get isoCode form GeoLite2?

我安装了 MaxMind 的 GeoLite2 和测试 php 文件:

<?php
require_once 'vendor/autoload.php';

use MaxMind\Db\Reader;
$ipAddress = '8.8.8.8';
$databaseFile = './GeoLite2-Country.mmdb';

$reader = new Reader($databaseFile);

print_r($reader->get($ipAddress));

$reader->close();

给我这些结果:

Array ( [continent] => Array ( [code] => NA [geoname_id] => 6255149 [names] => Array ( [de] => Nordamerika [en] => North America [es] => Norteamérica [fr] => Amérique du Nord [ja] => 北アメリカ [pt-BR] => América do Norte [ru] => Ð¡ÐµÐ²ÐµÑ€Ð½Ð°Ñ Ðмерика [zh-CN] => 北美洲 ) ) [country] => Array ( [geoname_id] => 6252001 [iso_code] => US [names] => Array ( [de] => USA [en] => United States [es] => Estados Unidos [fr] => États-Unis [ja] => アメリカåˆè¡†å›½ [pt-BR] => Estados Unidos [ru] => СШР[zh-CN] => 美国 ) ) [registered_country] => Array ( [geoname_id] => 6252001 [iso_code] => US [names] => Array ( [de] => USA [en] => United States [es] => Estados Unidos [fr] => États-Unis [ja] => アメリカåˆè¡†å›½ [pt-BR] => Estados Unidos [ru] => СШР[zh-CN] => 美国 ) ) ) 

我需要的只是 isoCode(在本例中是美国),有人知道如何从 GeoLite2 中获取 "US" 而不是整个数组吗?

这就是MaxMind's database reader的设计方式;它总是 returns 每次查找的完整记录。

您可以通过直接访问返回数组的元素来获取您感兴趣的特定信息:

// Fetch the database record for this IP address
$record = $reader->get($ipAddress);

// Output just the ISO country code ("US", in this case)
echo $record['country']['iso_code'] . PHP_EOL;

修改您的示例:

<?php
require_once 'vendor/autoload.php';

use MaxMind\Db\Reader;
$ipAddress = '8.8.8.8';
$databaseFile = './GeoLite2-Country.mmdb';

$reader = new Reader($databaseFile);

$record = $reader->get($ipAddress);

print($record['country']['iso_code']);

$reader->close();

或使用 GeoIp2 API:

<?php
require_once 'vendor/autoload.php';
use GeoIp2\Database\Reader;


$reader = new Reader('/usr/local/share/GeoIP/GeoIP2-City.mmdb');


$record = $reader->city('8.8.8.8');
print($record->country->isoCode);