我需要从访客IP中获取州和国家。我将使用国家信息来展示定制的产品。至于状态信息,它不会用于相同的目的,而只是用于记录,以跟踪需求。
我在这个站点上找到了一个使用ipinfo.io应用编程接口的实例,其中包含以下示例代码:
function ip_details($ip) {
$json = file_get_contents("http://ipinfo.io/{$ip}/json");
$details = json_decode($json);
return $details;}
然而,由于我不需要完整的细节,我看到该网站只允许抓取单个字段。因此,我正在考虑使用这两个:
1) ipinfo.io/{ip}/region 2) ipinfo.io/{ip}/country
如下所示:
function ip_details($ip) {
$ip_state = file_get_contents("http://ipinfo.io/{$ip}/region");
$ip_country = file_get_contents("http://ipinfo.io/{$ip}/country");
return $ip_state . $ip_country;}
或者我会更好的选择:
function ip_details($ip) {
$json = file_get_contents("http://ipinfo.io/{$ip}/geo");
$details = json_decode($json);
return $details;}
最后一个在url中有"/geo“,以减少第一个带有"/json”的选择。目前,我倾向于使用上面的第二个选项,使用2 file_get_contents,但想知道它是否比上一个在数组中的慢。只是想最小化加载时间。或者,如果能给出任何其他方法,将不胜感激。
发布于 2014-08-13 19:13:03
简而言之,使用您的第二种选择,只需一个请求(file_get_contents在解析url时发出get请求):
结果是一个简单的数组,通过它的键访问你想要的细节:
function ip_details($ip) {
$json = file_get_contents("http://ipinfo.io/{$ip}/geo");
$details = json_decode($json);
return $details;
}
$ipinfo = ip_details('86.178.xxx.xxx');
echo $ipinfo['country']; //GB
//etc关于速度差异- 99%的开销是网络延迟,所以发出一个请求并解析所需的细节将比对单个细节发出两个单独的请求要快得多
https://stackoverflow.com/questions/25284523
复制相似问题