我如何从这些数据中选择country_code?

时间:2014-07-26 11:13:51

标签: php json

这里我用这个

获得了以下数据
$location = file_get_contents('http://freegeoip.net/json/'.$_SERVER['REMOTE_ADDR']);

和$ location包含:

{
      "ip": "77.99.179.98",
      "country_code": "GB",
      "country_name": "United Kingdom",
      "region_code": "H9",
      "region_name": "London, City of",
      "city": "London",
      "zipcode": "",
      "latitude": 51.5142,
      "longitude": -0.0931,
      "metro_code": "",
      "areacode": ""

}

已收到此数据。但是我没有得到如何粉色country_name和region_name?

5 个答案:

答案 0 :(得分:0)

您可以像这样使用jsone_decode

    $output_string = '{
      "ip": "77.99.179.98",
      "country_code": "GB",
      "country_name": "United Kingdom",
      "region_code": "H9",
      "region_name": "London, City of",
      "city": "London",
      "zipcode": "",
      "latitude": 51.5142,
      "longitude": -0.0931,
      "metro_code": "",
      "areacode": ""

}';

$arr = json_decode($output_string, true);
echo "Country  Name :".$arr['country_name'];
echo "\nRegion  Name :".$arr['region_name'];

请参阅Working Demo

答案 1 :(得分:0)

试试这个

$obj = json_decode($location, true);

然后尝试获取对象

echo $obj['country_name'];

答案 2 :(得分:0)

$locationArray = json_decode($location, true);
echo $locationArray['country_name'];

答案 3 :(得分:0)

这有效:

$arr = json_decode('{
      "ip": "77.99.179.98",
      "country_code": "GB",
      "country_name": "United Kingdom",
      "region_code": "H9",
      "region_name": "London, City of",
      "city": "London",
      "zipcode": "",
      "latitude": 51.5142,
      "longitude": -0.0931,
      "metro_code": "",
      "areacode": ""

}');

echo $arr->country_code . ", " . $arr->country_name;

true添加json_decode($json_string, true)参数,以返回数组而不是上面的对象。

$arr = json_decode('{
      "ip": "77.99.179.98",
      "country_code": "GB",
      "country_name": "United Kingdom",
      "region_code": "H9",
      "region_name": "London, City of",
      "city": "London",
      "zipcode": "",
      "latitude": 51.5142,
      "longitude": -0.0931,
      "metro_code": "",
      "areacode": ""

}', true);

echo $arr['country_code'] . ", " . $arr['country_name'];

答案 4 :(得分:-2)

使用$location->country_code;它会为您提供国家/地区代码。