sergio
sergio

Reputation: 5260

Magento : Get country code by country name

I have tried to find country code by country name. So, for example, I have "Netherlands", I need to get "NL"

I know there is method to find name form code:

$country_name = Mage::app()->getLocale()->getCountryTranslation($country_code) 

But I need vice versa.
So is there any methods in Magento to resolve it?

Upvotes: 4

Views: 14975

Answers (5)

in Magento 2 there is a lack of simple processes so i suggest you to use the zend framework like :

$countryId = array_search($countryName, \Zend_Locale::getTranslationList('territory'));

Don't forget to make sure your country name is capitalized.

Upvotes: 1

Bejoy
Bejoy

Reputation: 311

This works for me $list = Mage::app()->getLocale()->getCountryTranslationList(); $list=array_flip($list); echo $list['United States'];

Upvotes: 5

Arkadij Kuzhel
Arkadij Kuzhel

Reputation: 199

There is a way to get Country ID without loading countries collection. As all country IDs mapped with names are stored in XML you can access that XML by locale object.

$list = Mage::app()->getLocale()->getCountryTranslationList();
foreach ($list as $id => $name) {
    if ($name == $countryName) {
        return $id;
    }
}

Please note that country name should be translated to the current locale language. Otherwise change locale to necessary one:

$oldCode = Mage::app()->getLocale()->getLocaleCode();
Mage::app()->getLocale()->setLocaleCode('en_US');
...
...
...
Mage::app()->getLocale()->setLocaleCode($oldCode);

Upvotes: 2

Rahul Shinde
Rahul Shinde

Reputation: 1662

the country collection

        <select title="Country" class="validate-select" id="billing:country_id"                      name="billing[country_id]">
             <option value=""> </option>
             <?php
                 $collection = Mage::getModel('directory/country')->getCollection();    
                 foreach ($collection as $country) 
                 {
                    ?>
                     <option value="<?php echo $country->getId(); ?>"><?php echo $country->getName(); ?></option>
                    <?php 
                }
            ?>
       </select>

Upvotes: 0

Steve Robbins
Steve Robbins

Reputation: 13812

From the other question, this can only be done by looping through the country collection

$countryId = '';
$countryCollection = Mage::getModel('directory/country')->getCollection();
foreach ($countryCollection as $country) {
    if ($countryName == $country->getName()) {
        $countryId = $country->getCountryId();
        break;
    }
}
echo $countryId;

Because of how the data is stored in the XML there is no way to filter or load by name.

Upvotes: 5

Related Questions