简体   繁体   中英

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?

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.

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

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);

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM