【发布时间】:2014-01-27 13:02:38
【问题描述】:
嗨,我想从 IP 地址获取国家代码数据
该网站提供免费服务,例如此链接
http://freegeoip.net/json/23.94.30.210
此链接显示所有数据,但我只需要其中的"country_code":"US"。
请告诉我如何在 php 中实现此链接,从中获取 "country_code":"US"。
【问题讨论】:
嗨,我想从 IP 地址获取国家代码数据
该网站提供免费服务,例如此链接
http://freegeoip.net/json/23.94.30.210
此链接显示所有数据,但我只需要其中的"country_code":"US"。
请告诉我如何在 php 中实现此链接,从中获取 "country_code":"US"。
【问题讨论】:
使用函数file_get_contents。
$jsonData = file_get_contents("http://freegeoip.net/json/23.94.30.210");
$countryInfo = json_decode($jsonData,true);
DEMO.
【讨论】:
首先,请参阅相关问题Getting visitors country from their IP。你可以使用Geo IP Location。
【讨论】:
看起来数据已经过 JSON 编码。您将需要使用 PHP 中可用的 JSON 函数对其进行解码,并检索国家代码(假设您已经设法使用 cURL 检索信息)。
这是一段代码示例:
// $data contains the information shown at http://freegeoip.net/json/23.94.30.210.
$decoded = json_decode($data);
$country_code = $decoded['country_code'];
【讨论】: