PHP: Display Country Flag Emoji From ISO 3166-1 alpha-2 Country Codes

A couple of weeks ago I wanted to display emoji country flags from 2 letter country codes. I couldn’t find PHP examples anywhere. Character encodings confuse me, but after looking at some JavaScript examples and other PHP encoding info I was able to get something working.

$country_code = 'US'; // Uppercase
echo mb_convert_encoding( '&#' . ( 127397 + ord( $country_code[0] ) ) . ';', 'UTF-8', 'HTML-ENTITIES');
echo mb_convert_encoding( '&#' . ( 127397 + ord( $country_code[1] ) ) . ';', 'UTF-8', 'HTML-ENTITIES');

For U this prints out 🇺 and for S it prints out 🇸. When those two characters are side by side they get displayed as 🇺🇸.

If you have an improvement or this helps you out, leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s