views:

51

answers:

3

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

+2  A: 

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.

Lèse majesté
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
Ah, sorry, I misunderstood your question.
Lèse majesté
+2  A: 

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/

madhurtanwani
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
+2  A: 

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"!

t-mow
...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