I have this code, which gets an array from a API URL.
<?php
$url = 'https://api.example.com/v1/w';
$data = file_get_contents($url);
$data = json_decode($data);
echo '<pre>' , var_dump($data->rule->deny_countries) , '</pre>';
?>
It displays this:
array(3) {
[0]=>
string(2) "US"
[1]=>
string(2) "ES"
[2]=>
string(2) "MX"
}
How can I only print the values of the strings? ( US, ES, and MX ) that are country codes, and i want to convert them to the full country name, example: United States, Spain, Mexico.
CodePudding user response:
You can print country code with this code:
$country_code = $data->rule->deny_countries;
echo $country_code[0]; // print US
echo $country_code[1]; // print ES
// ecc.
You can create an array to convert country code to country name like this:
$country_name = array("US"=>"United States", "ES"=>"Spain", "MX"=>"Mexico");
And then you can print country name with this code
echo $country_name[$country_code[0]]; // print United States
echo $country_name[$country_code[1]]; // print Spain
// ecc.
CodePudding user response:
Thank you to @Stefino76, this is working code:
<?php
$url = 'https://api.example.com/v1/9d';
$data = file_get_contents($url);
$data = json_decode($data);
$country_code = $data->rule->deny_countries;
$country_name = array("US"=>"United States", "ES"=>"Spain", "MX"=>"Mexico");
$img_file = array("AX"=>"united-states.png", "AD"=>"sp.png", "AS"=>"mx.png");
echo '<div><img src="'.$img_file[$country_code[0]].'">'.$country_name[$country_code[0]].'</div>';
echo '<div><img src="'.$img_file[$country_code[1]].'">'.$country_name[$country_code[1]].'</div>';
echo '<div><img src="'.$img_file[$country_code[2]].'">'.$country_name[$country_code[2]].'</div>';
?>