Reputation: 629
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?
Upvotes: 2
Views: 1749
Reputation: 71
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';
}
Upvotes: 0
Reputation: 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"}
Upvotes: 0
Reputation: 3703
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;
Upvotes: 1
Reputation: 7347
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)
Upvotes: 1
Reputation: 8700
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];
Upvotes: 3