Here is my Magento code:
private function getAllCountry() {
require_once("../app/Mage.php");
umask(0);
Mage::app("default");
$countryName = Mage::getModel('directory/country')->load('FR')->getName(); //get country name
echo 'Country Name ->'.$countryName.'<br/>';
$states = Mage::getModel('directory/country')->load('FR')->getRegions();//state names
foreach ($states as $state)
{
echo 'ID->'.$state->getId().'<br/>';
echo 'Name->'.$state->getName().'<br/>';
}
}
I want to get the list of all country names with their states and region id in an array.
Best Answer
Note that although these answers might work, they're not the proper Magento Way™ to do this. The right path to choose is to use Service Contract.
The Directory module comes with a very handy Service Contract called the "CountryInformationAcquirerInterface". You can find it at
Magento\Directory\Api\CountryInformationAcquirerInterface
. This has a very handy function calledgetCountriesInfo()
, which returns an array ofCountryInformation
data models, which - in their turn - have a method calledgetAvailableRegions()
. So the full example would look something like this:With most tasks in Magento 2, the best approach is to check first if there's a Service Contract that might fit your needs. Because most of the time, there is.