Friday, April 30, 2010

3:19 AM

I’ve used the API from to fetch the country name , city name and country code from the given IP address. I’ve mad this function in PHP which uses XML response from and extracted country name, city name and country code using regular expression.

Function to return country, city name from IP address in PHP

function countryCityFromIP($ipAddr)
//function to find country and city from IP address
//Developed by Roshan Bhattarai

//verify the IP address for the
ip2long($ipAddr)== -1 || ip2long($ipAddr) === false ? trigger_error("Invalid IP", E_USER_ERROR) : "";
$ipDetail=array(); //initialize a blank array

//get the XML result from
$xml = file_get_contents("".$ipAddr);

//get the city name inside the node <gml:name> and </gml:name>

//assing the city name to the array

//get the country name inside the node <countryName> and </countryName>

//assign the country name to the $ipDetail array

//get the country name inside the node <countryName> and </countryName>
$ipDetail['country_code']=$cc_match[1]; //assing the country code to array

//return the array containing city, country and country code
return $ipDetail;


As you can see, I’ve documented all the PHP code and I don’t think I need explain anymore about that code. Just notice that, this function returns the array containg three key elements “country” , “city” and “country_code”. Each elements have the value of city, country and country code.
Now, look the the how we can use the above function in PHP,

echo $IPDetail['country']; //country of that IP address
echo $IPDetail['city']; //outputs the IP detail of the city

Notice that the above PHP function returns the array containing the country , city and country code from IP Address and we can use them in PHP. If you want to know how to get IP address in PHP, you can check this post how you can get real IP address in PHP.


priya said...

m not getting city from this code