Last active
August 29, 2015 14:26
-
-
Save kslimani/069977c1b8ea506cd39a to your computer and use it in GitHub Desktop.
PHP Helper class which extract GeoIP ISO 3166 multi-languages country Codes list from Maxmind website
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Helper class which extract GeoIP ISO 3166 country Codes list from Maxmind website. | |
*/ | |
class MaxMindIso3166 | |
{ | |
/** | |
* Maxmind CSV download url. | |
* | |
* @var string | |
*/ | |
protected static $csvUrl = "http://dev.maxmind.com/static/csv/codes/iso3166.csv"; | |
/** | |
* CSV cache file pathname. | |
* | |
* @var string | |
*/ | |
protected static $cachefile = '/tmp/iso3166.csv'; | |
/** | |
* Expiry in seconds. | |
* | |
* @var int | |
*/ | |
protected static $expiry = 3600; | |
/** | |
* Download country codes in CSV format. | |
* | |
* @return string The CSV raw data | |
*/ | |
protected static function downloadCsv() | |
{ | |
return trim(file_get_contents(self::$csvUrl)); | |
} | |
/** | |
* Verify is temporary CSV cache file is expired. | |
* | |
* @return bool true if expired, otherwise false | |
*/ | |
protected static function fileIsExpired() | |
{ | |
return ((time() - filemtime(self::$cachefile)) > self::$expiry); | |
} | |
/** | |
* Get country codes in CSV format. | |
* | |
* @return string The CSV raw data | |
*/ | |
protected static function getCsv() | |
{ | |
if (is_file(self::$cachefile) && !self::fileIsExpired()) { | |
// Get from cache file | |
return file_get_contents(self::$cachefile); | |
} else { | |
// Download & save to cache file | |
$csv = self::downloadCsv(); | |
file_put_contents(self::$cachefile, $csv); | |
return $csv; | |
} | |
} | |
/** | |
* Get Maxmind GeoIP ISO 3166 Country Codes. | |
* | |
* @param string $inLocale Optional format locale | |
* to use to translate country name | |
* | |
* @return array The country codes | |
*/ | |
public static function getCountryCodes($inLocale = 'fr') | |
{ | |
$countryCodes = []; | |
$lines = explode("\n", self::getCsv()); | |
foreach ($lines as $line) { | |
list($code, $name) = str_getcsv($line); | |
// Use Locale to translate country name | |
$countryName = Locale::getDisplayRegion( | |
sprintf('-%s', $code), | |
$inLocale | |
); | |
// If translation failed, keep original name | |
// Always happen for 'A1', 'A2' and 'O1' codes | |
if ($countryName === $code) { | |
$countryName = $name; | |
} | |
$countryCodes[$code] = $countryName; | |
} | |
return $countryCodes; | |
} | |
} | |
$codes = MaxMindIso3166::getCountryCodes(); | |
var_export($codes); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment