In this post I am going to explain how to get country name from country code in Magento 2.
1. Using Dependency Injection
Add below code snippet in Block class.
protected $_countryFactory;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Directory\Model\CountryFactory $countryFactory,
array $data = []
)
{
$this->_countryFactory = $countryFactory;
parent::__construct($context, $data);
}
public function getCountryName($countryCode)
{
$country = $this->_countryFactory->create()->loadByCode($countryCode);
return $country->getName();
}Add below code snippet in template file.
//Your country code $countryCode = 'US'; // Get country name $countryName = $block->getCountryname($countryCode); echo $countryName;
2. Using Object Manager
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$countryFactory = $objectManager->get('Magento\Directory\Model\CountryFactory')->create();
//Your country code
$countryCode = 'US';
// Get country name
$country = $countryFactory->loadByCode($countryCode);
$countryName = $country->getName();
echo $countryName;
Write an article about ecommerce that help people to grow their ecommerce business. You’ll find best ecommerce guide, news, tips & more!


Leave a Reply