I need to load the 2 letter ISO2 country ID for a given country name.
Right now, I use the following method to do this:
// Method to Get countryId from CountryName
function getCountryId($countryName) {
$countryId = '';
$countryCollection = Mage::getModel('directory/country')->getCollection();
foreach ($countryCollection as $country) {
if ($countryName == $country->getName()) {
$countryId = $country->getCountryId();
break;
}
}
$countryCollection = null;
return $countryId;
}
Usage:
var_dump(getCountryId('Germany'));
Outputs:
string(2) "DE"
Is there a easier/quicker way to do this instead of loading the country collection and iterating through it every time?
Surprisingly, looping is the only way you'll achieve this.
The country names are stored in XML files in lib/Zend/Locale/Data/
and they're organized by locale (en, es, fr) and then country code, not country name.
Since it's not a SQL table you can't add a WHERE
clause (using Magento's addFieldToFilter()
), so you'll be looping through the XML nodes anyway.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With