Search code examples
phpgeoipmaxmind

How to get isoCode form GeoLite2?


I have a GeoLite2 from MaxMind installed and the test php file:

<?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();

Gives me these results:

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] => 美国 ) ) ) 

What I need is just the isoCode (in this case US), anyone know how to get just "US" from GeoLite2 not that whole Array?


Solution

  • This is the way MaxMind's database reader is designed; it always returns the full record for every lookup.

    You can get the specific piece of information you're interested in by accessing elements of the returned array directly:

    // 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;