Skip to content

Instantly share code, notes, and snippets.

@Bodom78
Created September 22, 2021 05:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Bodom78/4333fca67c5f306eb6a44f0f8fa696c5 to your computer and use it in GitHub Desktop.
Save Bodom78/4333fca67c5f306eb6a44f0f8fa696c5 to your computer and use it in GitHub Desktop.
Create a PHP array of Country Codes and Names
<?php
/**
* Will write/overwrite an array to countries_en.php in the same directory.
* $countries = [
* "AW" => "Aruba",
* "AF" => "Islamic Republic of Afghanistan",
* "AO" => "Republic of Angola",
* "AI" => "Anguilla",
* ...
* @see https://restcountries.com for more information.
*/
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://restcountries.com/v3/all');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
$countries = json_decode($result);
$filename = 'countries_en.php';
file_put_contents($filename,
"<?php\n\n\$countries = [\n");
foreach ($countries as $country) {
$country_code = $country->cca2;
$country_name = $country->name->official;
file_put_contents($filename,
"\t".'"'.$country_code.'" => "'.$country_name.'",'.PHP_EOL, FILE_APPEND);
}
file_put_contents($filename, "];", FILE_APPEND);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment