I have the following script that uses the api on hostip.info. The page parses an xml readout of a user location based on the ip address. In my function everything is working except for the city.
preg_match("@<Hostip>(\s)*<gml:name>(.*?)</gml:name>@si",$xml,$city_match);
I have narrowed it down to my preg_match being wrong but I'm not sure how to fix it. Here is a sample xml output: http://api.hostip.info/?ip=12.215.42.19
<?php
function getCountryCity()
{
if(isset($_SERVER['REMOTE_ADDR']) && strlen($_SERVER['REMOTE_ADDR']) > 0) {
$ipAddr = $_SERVER['REMOTE_ADDR'];
// verify the IP address
ip2long($ipAddr)== -1 || ip2long($ipAddr) === false ? trigger_error("Invalid IP", E_USER_ERROR) : "";
$ipDetail=array();
// get the XML result from hostip.info
$xml = file_get_contents("http://api.hostip.info/?ip=".$ipAddr);
// get the city name inside the node <gml:name> and </gml:name>
preg_match("@<Hostip>(\s)*<gml:name>(.*?)</gml:name>@si",$xml,$city_match);
$ipDetail['city'] = $city_match[1];
// get the country name inside the node <countryName> and </countryName>
preg_match("@<countryName>(.*?)</countryName>@si",$xml,$country_match);
$ipDetail['country'] = $country_match[1];
// get the country name inside the node <countryName> and </countryName>
preg_match("@<countryAbbrev>(.*?)</countryAbbrev>@si",$xml,$cc_match);
$ipDetail['country_code'] = $cc_match[1];
// return the array containing city, country and country code
return $ipDetail;
} else {
return false;
}
}
$ipDetail = getCountryCity();
$user_city = $ipDetail['city'];
$user_country = $ipDetail['country'];
$user_cc = $ipDetail['country_code'];
echo $user_country.' ('.$user_cc.')';
echo $user_city;
?>