Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Magento - Get Country Id from Name - is there a easier/quicker way?

Tags:

magento

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?

like image 804
Latheesan Avatar asked Nov 01 '22 14:11

Latheesan


1 Answers

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.

like image 126
Steve Robbins Avatar answered Jan 04 '23 13:01

Steve Robbins