15

i want to get country name from country code, i got the country code from the data order like this :

$data = $order->getShippingAddress()->getData();
$countryCode = $data['country_id'];
echo $countryCode;

it will print 'US' or any other country code, is there a way to get the country name from this country code?

1

7 Answers 7

44

Create Block file,

   public function __construct(
            \Magento\Directory\Model\CountryFactory $countryFactory
        ) {
            $this->_countryFactory = $countryFactory;
        }
    
    public function getCountryname($countryCode){    
        $country = $this->_countryFactory->create()->loadByCode($countryCode);
        return $country->getName();
    }

Call from phtml file,

<?= $block->getCountryname($countryCode);?>
3
  • 1
    Correct except you are missing a semi colon after $country = $this->_countryFactory->create()->loadByCode($countryCode) it should be $country = $this->_countryFactory->create()->loadByCode($countryCode);
    – Eirik
    May 6, 2017 at 18:16
  • Is it possible to get country code from country name?
    – Vindhuja
    Nov 29, 2018 at 6:20
  • @Vindhuja Check rakeshjesadiya.com/… Nov 29, 2018 at 6:29
11

We can use Magento\Directory\Api\CountryInformationAcquirerInterface to get the country info:

/** @var \Magento\Directory\Api\CountryInformationAcquirerInterface $country */

/** @var \Magento\Directory\Api\Data\CountryInformationInterface $data */
    $data = $country->getCountryInfo($data['country_id']);
    $data->getFullNameEnglish();
    $data->getFullNameLocale();

See more here about the returned values: Magento\Directory\Api\Data\CountryInformationInterface

2
  • Hi, Can you please tell me, how to use this for getting engilsh country name in magento 2
    – Ask Xah
    Sep 21, 2019 at 10:11
  • This is just perfect. i write a article based on this solution for details blog.equaltrue.com/… this can be help you @AskBytes Jan 1, 2020 at 16:24
1

In the below example, in one of the task I need to print pdf on a custom way, that’s why I need the billing address country and the shipping address country but, from sales order data I get it on as country id like “SE” (for Sweden)

in the method, you can value in two way on method getCountryName(), in English or in local.

CountryInformationAcquirerInterface is used here.

here is the full code

namespace Equaltrue\Orderprint\Block\Order;

use Magento\Backend\Block\Template\Context;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Registry;
use Magento\Framework\View\Element\Template;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Directory\Api\CountryInformationAcquirerInterface;

class Print extends Template
{
    protected $_coreRegistry;
    protected $orderRepository;
    protected $countryInformationAcquirerInterface;

    /**
     * Constructor
     *
     * @param CountryInformationAcquirerInterface $countryInformationAcquirerInterface
     * @param OrderRepositoryInterface $orderRepository
     * @param Context $context
     * @param Registry $coreRegistry
     * @param array $data
     */
    public function __construct(
        CountryInformationAcquirerInterface $countryInformationAcquirerInterface,
        OrderRepositoryInterface $orderRepository,
        Context $context,
        Registry $coreRegistry,
        array $data = []
    ) {
        $this->orderRepository = $orderRepository;
        $this->countryInformationAcquirerInterface = $countryInformationAcquirerInterface;
        $this->_coreRegistry = $coreRegistry;
        parent::__construct($context, $data);
    }

    /**
     * Retrieve Current Data
     */
    public function getOrderData()
    {
        $orderId = $this->getRequest()->getParam('order_id', 0);
        $order =  $this->getOrder($orderId);

        /*
         * Get billing Address
         * */
        $billingAddress = $order->getBillingAddress();
        $firstNameBilling = $billingAddress->getFirstName();
        $lastNameBilling = $billingAddress->getLastName();
        $streetBilling = implode( ", ", $billingAddress->getStreet());
        $cityBilling = $billingAddress->getCity();
        $postCodeBilling = $billingAddress->getPostCode();
        $countryIdBilling = $billingAddress->getCountryId();
        $countryNameBilling = $this->getCountryName($countryIdBilling);
        $telephoneBilling = "T: ".$billingAddress->getTelephone();
        $formattedBillingAddress = $firstNameBilling." ".$lastNameBilling."<br>". $streetBilling."<br>". $cityBilling.",".$postCodeBilling."<br>".$countryNameBilling."<br>".$telephoneBilling;

        /*
         * Get billing Address
         * */
        $shippingAddress = $order->getShippingAddress();
        $firstNameShipping = $shippingAddress->getFirstName();
        $lastNameShipping = $shippingAddress->getLastName();
        $streetShipping = implode( ", ", $shippingAddress->getStreet());
        $cityShipping = $shippingAddress->getCity();
        $postCodeShipping = $shippingAddress->getPostCode();
        $countryIdShipping = $billingAddress->getCountryId();
        $countryNameShipping = $this->getCountryName($countryIdShipping);
        $telephoneShipping = "T: ".$shippingAddress->getTelephone();
        $formattedShippingAddress = $firstNameShipping." ".$lastNameShipping."<br>". $streetShipping."<br>". $cityShipping.",".$postCodeShipping."<br>".$countryNameShipping."<br>".$telephoneShipping;

        return array(
            "formatted_billing_address" => $formattedBillingAddress,
            "formatted_shipping_address" => $formattedShippingAddress
        );
    }

    /**
     * Getting Country Name
     * @param string $countryCode
     * @param string $type
     *
     * @return null|string
     * */
    public function getCountryName($countryCode, $type="local"){
        $countryName = null;
        try {
            $data = $this->countryInformationAcquirerInterface->getCountryInfo($countryCode);
            if($type == "local"){
                $countryName = $data->getFullNameLocale();
            }else {
                $countryName = $data->getFullNameLocale();
            }
        } catch (NoSuchEntityException $e) {}
        return $countryName;
    }

    protected function getOrder($id)
    {
        return $this->orderRepository->get($id);
    }
}
0

Check the given model of country and its methods:

/**
     * 
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
     * @param \Magento\Directory\Model\CountryFactory $countryFactory
     */
    public function __construct(
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, 
        \Magento\Directory\Model\CountryFactory $countryFactory    
    ) {  
        $this->scopeConfig = $scopeConfig;
        $this->countryFactory = $countryFactory;
    }

One of the method it provides is $this->countryFactory->create()->getName(); .You can use the model factory based on your requirements.

0

I've been working on this for the order success page. The easiest method to call it in a phtml file is to use:

    $countrycode = $order->getShippingAddress()->getData("country_id");
    $country = $objectManager->create('\Magento\Directory\Model\Country')- 
    >load("$countrycode")->getName();
    echo $country;

The customer_address_entity table doesn't hold the country but does hold the country code. This gets the country code from the order and loads the country name associated with it.

-2

Get country name by country code using objectManager.

<?php
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $countryCode = 'US'; // Enter country code here
    $country = $objectManager->create('\Magento\Directory\Model\Country')->load($countryCode)->getName();
    echo $country;
?>

Thanks

-4
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
            $allowerdContries = $objectManager->get('Magento\Directory\Model\AllowedCountries')->getAllowedCountries() ;
            $countryFactory = $objectManager->get('\Magento\Directory\Model\CountryFactory');
            //echo "<pre>"; print_r($allowerdContries);

            $countries = array();
            foreach($allowerdContries as $countryCode)
            {
                    if($countryCode)
                    {

                        $data = $countryFactory->create()->loadByCode($countryCode);
                        $countries[$countryCode] =  $data->getName();
                    }
            }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.