2

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?

Alnitak
  • 334,560
  • 70
  • 407
  • 495
SohailRajput
  • 629
  • 1
  • 7
  • 18

6 Answers6

3

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];
Jess
  • 8,628
  • 6
  • 49
  • 67
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)
Glycerine
  • 7,157
  • 4
  • 39
  • 65
1

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;
Imi Borbas
  • 3,683
  • 1
  • 19
  • 16
0

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"}

0
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';
}
John O
  • 71
  • 1
  • 3
0

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