https://rapidweb.biz/wp-content/uploads/2018/02/php-countries-featured-image-1024x726.jpg

Get Country Code in PHP, with PHP Countries


Country information is used so frequently in modern web development. This is especially true in customer relationship managements systems and e-commerce websites.

Since we do a lot of e-commerce and CRM development here at Rapid Web Services, we developed an open source library to easily retrieve country information. The rest of this post will detail how you can use this library, PHP Countries, and what it is capable of.

Installation

To install PHP Countries, just run the following Composer command.

composer require rapidwebltd/php-countries

If you’re never used Composer, take a look at the Composer website for instructions on how to install and use it.

Usage

There are many features of PHP Countries. Here are just a few.

Retrieving Country Code

To retrieve a country code from a country name, just call the getByName method to retrieve a Country object and then access its isoCodeAlpha3 property.

$country = (new Countries)->getByName('United Kingdom');
// $country->isoCodeAlpha3 == 'GBR'
// $country->isoCodeAlpha2 == 'GB'

Retrieving Country details by Country Code

PHP Countries provides a large amount of details on countries, which can be retrieved in many ways. This information includes the country’s full name, official name, languages spoken, currencies used, and more.

One of the ways to retrieve these details is by the country’s ISO code. Both the 2 and 3 character versions are supported.

var_dump((new Countries)->getByIsoCode('GBR'));

/*
object(RapidWeb\Countries\Country)#4869 (16) {
["name"]=>
string(14) "United Kingdom"
["officialName"]=>
string(52) "United Kingdom of Great Britain and Northern Ireland"
["topLevelDomains"]=>
array(1) {
[0]=>
string(3) ".uk"
}
["isoCodeAlpha2"]=>
string(2) "GB"
["isoCodeAlpha3"]=>
string(3) "GBR"
["isoCodeNumeric"]=>
string(3) "826"
["languages"]=>
array(1) {
[0]=>
string(7) "English"
}
["languageCodes"]=>
array(1) {
[0]=>
string(3) "eng"
}
["currencyCodes"]=>
array(1) {
[0]=>
string(3) "GBP"
}
["callingCodes"]=>
array(1) {
[0]=>
string(2) "44"
}
["capital"]=>
string(6) "London"
["region"]=>
string(6) "Europe"
["subregion"]=>
string(15) "Northern Europe"
["latitude"]=>
int(54)
["longitude"]=>
int(-2)
["areaInKilometres"]=>
int(242900)
}
*/

Retrieving Country details for All Countries

In order to retrieve an array of Country objects for every country, just call the ‘all()’ method on the main Countries object.

foreach((new Countries)->all() as $country) {
var_dump($country->name.' - '.$country->officialName);
}

Additional Usage & Contributions

For more documentation and additional usage examples, see the PHP Countries GitHub page. Any contributions are most welcome!

Please take a look at some of our open source projects or read some of our blog posts about open source software.