简体   繁体   English

IP地理定位的PHP和API

[英]PHP & API for IP Geolocation

I am trying to use http://www.hostip.info/use.html in my web app to show the approximate City location of an IP address. 我试图在我的Web应用程序中使用http://www.hostip.info/use.html来显示IP地址的大致城市位置。 I cannot figure out how to actually show the contents of the API... Here is what I have that is not working. 我无法弄清楚如何真正显示API的内容...这是我无法使用的内容。

function showCity($currIP){

$lookupData = 'http://api.hostip.info/get_html.php?ip='.$currIP;
return $lookupData;

}

Your API returns this: 您的API返回以下内容:

Country: UNITED STATES (US)
City: Seattle, WA
IP: 168.111.127.225

So you need to do some string parsing on that result. 因此,您需要对该结果进行一些字符串解析。 Using the below will get your started: 使用以下内容可以开始使用:

 $array = preg_split('/$\R?^:/m', $lookupData);
 print_r($array);

Try this instead: 尝试以下方法:

$array = preg_split("/[\r\n]/", $lookupData, -1, PREG_SPLIT_NO_EMPTY);

Also, as was mentioned by mcmajkel, if you use the JSON api link, you can get to it with this: 另外,如mcmajkel所提到的,如果您使用JSON api链接,则可以使用以下方法进行访问:

$lookupData = 'http://api.hostip.info/get_json.php?ip='.$currIP;
$api = json_decode($lookupData);
$myName = $api->country_name;
$myCode = $api->country_code;
$myCity = $api->city;
$myIP   = $api->ip;

This call returns string, as mentioned by GregP. 如GregP所述,此调用返回字符串。 But you can call http://api.hostip.info/get_json.php?ip=12.215.42.19 但是您可以致电http://api.hostip.info/get_json.php?ip=12.215.42.19

And get a nice piece of JSON in return, which will be easier to parse 并获得一个不错的JSON作为回报,它将更易于解析

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM