php: How to determine the country by ip address

How to find the coutry by ip address

function countryCityFromIP($ipAddr)
{
//function to find country and city from IP address
//Developed by Roshan Bhattarai [url]http://roshanbh.com.np[/url]

[php]
//verify <strong class="highlight">the</strong> <strong class="highlight">IP</strong> address for <strong class="highlight">the</strong>
ip2long($ipAddr)== -1 || ip2long($ipAddr) === false ? trigger_error("Invalid <strong class="highlight">IP</strong>", E_USER_ERROR) : "";
$ipDetail=array(); //initialize a blank array

//get <strong class="highlight">the</strong> XML result from hostip.info
$xml = file_get_contents("http://api.hostip.info/?ip=".$ipAddr);

//get <strong class="highlight">the</strong> city name inside <strong class="highlight">the</strong> node <gml:name> and </gml:name>
preg_match("@<Hostip>(\s)*<gml:name>(.*?)</gml:name>@si",$xml,$match);

//assing <strong class="highlight">the</strong> city name <strong class="highlight">to</strong> <strong class="highlight">the</strong> array
$ipDetail['city']=$match[2];

//get <strong class="highlight">the</strong> <strong class="highlight">country</strong> name inside <strong class="highlight">the</strong> node <countryName> and </countryName>
preg_match("@<countryName>(.*?)</countryName>@si",$xml,$matches);

//assign <strong class="highlight">the</strong> <strong class="highlight">country</strong> name <strong class="highlight">to</strong> <strong class="highlight">the</strong> $ipDetail array
$ipDetail['<strong class="highlight">country</strong>']=$matches[1];

//get <strong class="highlight">the</strong> <strong class="highlight">country</strong> name inside <strong class="highlight">the</strong> node <countryName> and </countryName>
preg_match("@<countryAbbrev>(.*?)</countryAbbrev>@si",$xml,$cc_match);
$ipDetail['country_code']=$cc_match[1]; //assing <strong class="highlight">the</strong> <strong class="highlight">country</strong> code <strong class="highlight">to</strong> array

//return <strong class="highlight">the</strong> array containing city, <strong class="highlight">country</strong> and <strong class="highlight">country</strong> code
return $ipDetail;

}
[/php]

Technorati Tags: php country by ip, how to country by ip