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 Answers
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.

- 7,923
- 2
- 33
- 44
-
Thanks for the Tip Lèse but indeed this part is covered by Zend_Locale. It's the conversion of the country back to the code where the country can be written in different languages that gives me a problem here. – Peter Jul 07 '10 at 04:59
-
Ah, sorry, I misunderstood your question. – Lèse majesté Jul 07 '10 at 05:41
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/

- 1,199
- 7
- 13
-
Cool stuff, thank you for introducing this to me. At the moment I want to keep my code "indoors" but this is definitely going to come in handy one day. – Peter Jul 07 '10 at 05:44
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"!

- 90
- 1
- 5
-
...and so simple the solution can be. Specially as I only allow a few countries in a few languages and so the array_search is swift. I bundled it all up in a Filter and I'm good to go. Thanks! – Peter Jul 07 '10 at 05:45
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.

- 3,884
- 1
- 30
- 27

- 31
- 3