将国家/地区代码映射到国家/地区名称php

时间:2017-09-22 16:14:20

标签: php json

我有一个功能,我在这里找到用户ip到国家。但它只显示我要显示完整国家和abrev的abrev

function ip_details($IPaddress)
{
    $json       = file_get_contents("http://ipinfo.io/{$IPaddress}");
    $details    = json_decode($json);
    return $details;
}

$IPaddress  =  'get ip here';

$details    =   ip_details("$IPaddress");

echo $details->region;
echo $details->country;

然后我回想起我想要的地方。

<?php echo $details->country;?>

所以我去了IpInfo Site

它告诉我下载和映射我已经下载了json文件,但不确定如何映射它以便我可以在需要时回显完整的国家/地区名称

4 个答案:

答案 0 :(得分:2)

我会从JSON中获取国家/地区代码,并在代码中创建一个PHP数组,以便快速查找。

$countryCodes = ['BD'=>'Bangladesh', ...];

if ( array_key_exists($details->country, $countryCodes) {
  $country = $countryCodes[$details->country];
}

答案 1 :(得分:2)

此代码段从JSON获取我认为您想要的输出。

一旦您对此脚本感到满意,就可以用硬编码的IP地址替换脚本中的值。

* * * * *  command to execute
│ │ │ │ │
│ │ │ │ └─── day of week (0 - 6) (0 to 6 are Sunday to Saturday, or use names; 7 is Sunday, the same as 0)
│ │ │ └──────── month (1 - 12)
│ │ └───────────── day of month (1 - 31)
│ └────────────────── hour (0 - 23)
└─────────────────────── min (0 - 59)

输出:

$countries = json_decode(file_get_contents('http://country.io/names.json'));
$details = json_decode(file_get_contents("http://ipinfo.io/8.8.8.8"));
$code = $details->country;
echo "Country Name: ".$countries->$code."<br/>";
echo "Country Code: ".$code."<br/>";
echo "Region: ".$details->region."<br/>";
echo "City: ".$details->city."<br/>";

答案 2 :(得分:1)

您可以使用以下功能从国家/地区代码中获取国家/地区名称:

function getCountryName($code) {
    $json = file_get_contents("http://country.io/names.json");
    $countries = json_decode($json, TRUE);

    return array_key_exists($code,$countries) ? $countries[$code] : false;
}

作为改进,您可以下载http://country.io/names.json json文件并在此处引用它,而不是每次都远程调用它。

答案 3 :(得分:-1)

您需要使用PHP的json_decode函数将JSON数据转换为数组。

示例:

$country_json = file_get_contents('http://country.io/names.json');
$country_array = json_decode($country_json, TRUE); // TRUE turns the result into an associative array

echo $country_array[$details->country];
相关问题