Skip to content

Instantly share code, notes, and snippets.

@kslimani
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kslimani/069977c1b8ea506cd39a to your computer and use it in GitHub Desktop.
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
<?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