Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 870
Peter Avatar asked Dec 29 '22 11:12

Peter


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

like image 160
Lèse majesté Avatar answered Jan 12 '23 01:01

Lèse majesté