How to convert a country string to its ISO 3166-1 code using Zend?

6.4k Views Asked by At

Does anybody know if it's possible to use Zend_Locale to get the ISO 3166-1 code for a country if you have the country name as a string? For example I have "Nederland" so I would like to get "NL".

4

There are 4 best solutions below

1
On BEST ANSWER

You should have a look at Zend_Locale::getTranslation(). You may get a list (a simple array) of country names - and then you may use array_search() to get the needed "country-key"!

2
On

I don't know if Zend has something for that, but it's fairly easy to do on your own.

This tutorial shows how you can grab the latest list of ISO 3166-1 country codes in XML format, parse it, and then create a PHP file that can be included when you need a country code translation array:

$str = file_get_contents('http://opencountrycodes.appspot.com/xml/');
$xml = new SimpleXMLElement($str);
$out = '$countries'." = array(\n";
foreach ($xml->country as $country)
{
    $out .= "'{$country['code']}' => \"{$country['name']}\",\n";
}
$out .= ");";

file_put_contents('country_names.php', $out);

Alternately, you can save it as a CSV file and load it using PHP's fgetcsv() function. That would probably be preferable IMO. Or, heck, you could just save the XML and parse it when you load it.

1
On

I'm not sure how within Zend HTTp calls can be made, but here is probably a good resource to refer.

Use Yahoo!'s Geo data, which allows mapping of free form strings into WOE Ids. For countries, WOE Ids are the ISO 3166-1 codes.

To convert a free form string into a WOE Id, you can use the GeoPlanet APIs : http://developer.yahoo.com/geo/geoplanet/

0
On

I have made an up-to-date collection of countrynames and ISO 3166 country codes over at:

https://github.com/johannesl/Internationalization

You can use it to convert both name => country code and reverse.

I'm also creating a collection of common country aliases that will appear on github.