开发者

How can I parse the output from HostIP's geolocation API?

开发者 https://www.devze.com 2023-02-20 16:20 出处:网络
If I access the HostIP geolocation API via http://api.hostip.info/get_html.php?ip=193.148.1.1,it returns three lines of开发者_运维问答 text:

If I access the HostIP geolocation API via http://api.hostip.info/get_html.php?ip=193.148.1.1, it returns three lines of开发者_运维问答 text:

Country: SPAIN (ES)
City: (Unknown city)
IP: 193.148.1.1

How can I parse that output in PHP to extract the country name?


Try these preg_matches

$info = "Country: SPAIN (ES)
City: (Unknown city)
IP: 193.148.1.1";

preg_match("/Country: (.*)\n/", $info, $out);
echo $out[1];

## OR
preg_match ("/Country: (.*) \(.*\)?\n/", $info, $out);
echo $out[1];


Would some regex for PHP help?

if (preg_match('/Country: (.*[^\n\r])/i', $subject, $regs)) {
    $result = $regs[1];
} else {
    $result = "";
}

You will have: 

Match 1: Country: SPAIN (ES)
Group 1: SPAIN (ES)


You can obtain an XML response from hostip.info if you use the following URL:

http://api.hostip.info/?ip=193.148.1.1

instead of:

http://api.hostip.info/get_html.php?ip=193.148.1.1

Then, you can parse the XML which is kind of cleaner than Regex, and probably more immune to the possible changes of output formatting.

This is an example of parsing the output:

$response = file_get_contents('http://api.hostip.info/?ip=193.148.1.1');

$xml = new DOMDocument();
$xml->loadXml($response);

$xpath = new DOMXpath($xml);

$path = '/HostipLookupResultSet/gml:featureMember/Hostip/';

$ip = $xpath->evaluate($path . 'ip')->item(0)->nodeValue;
$city = $xpath->evaluate($path . 'gml:name')->item(0)->nodeValue;
$countryName = $xpath->evaluate($path . 'countryName')->item(0)->nodeValue;
$countryAbbrev = $xpath->evaluate($path . 'countryAbbrev')->item(0)->nodeValue;


country only: http://api.hostip.info/country.php?ip=193.148.1.1


http://api.hostip.info/get_json.php?position=true

{"country_name":"VENEZUELA","country_code":"VE","city":"Caracas","ip":"xxx.xx.xxx.xx","lat":"x.xxx","lng":"-xx.xxxx"}


function _get_country_from_IP($ip) {
  $data = json_decode(file_get_contents("http://ipinfo.io/{$ip}/json"));
  return $country = isset($data->country) ? $data->country : 'UNKNOWN';
}
0

精彩评论

暂无评论...
验证码 换一张
取 消