Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Regex for IP to Location API

How would I use Regex to get the information on a IP to Location API

This is the API

http://ipinfodb.com/ip_query.php?ip=74.125.45.100

I would need to get the Country Name, Region/State, and City.

I tried this:

$ip = $_SERVER["REMOTE_ADDR"];
$contents = @file_get_contents('http://ipinfodb.com/ip_query.php?ip=' . $ip . '');
$pattern = "/<CountryName>(.*)<CountryName>/";
preg_match($pattern, $contents, $regex);
$regex = !empty($regex[1]) ? $regex[1] : "FAIL";
echo $regex;

When I do echo $regex I always get FAIL how can I fix this

like image 980
xZerox Avatar asked Jun 27 '10 01:06

xZerox


People also ask

How to get location based on IP address in php?

Example in PHP: $data = file_get_contents("http://api.hostip.info/country.php?ip=12.215.42.19"); //$data contains: "US" $data = file_get_contents("http://api.hostip.info/?ip=12.215.42.19"); //$data contains: XML with country, lat, long, city, etc...

What is the regex for IP address?

// this is the regex to validate an IP address. = zeroTo255 + "\\." + zeroTo255 + "\\."

How do you get location from IP address?

There is no method of associating an exact physical geographical address or the computer associated with an IP address available to an end-user. If you need to report abuse by a person behind an IP address, contact local authorities or the ISP who's in control of that IP address.


1 Answers

As Aaron has suggested. Best not to reinvent the wheel so try parsing it with simplexml_load_string()

// Init the CURL
$curl = curl_init();

// Setup the curl settings
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 0);

// grab the XML file
$raw_xml = curl_exec($curl);

curl_close($curl);

// Setup the xml object
$xml = simplexml_load_string( $raw_xml );

You can now access any part of the $xml variable as an object, with that in regard here is an example of what you posted.

<Response> 
    <Ip>74.125.45.100</Ip> 
    <Status>OK</Status> 
    <CountryCode>US</CountryCode> 
    <CountryName>United States</CountryName> 
    <RegionCode>06</RegionCode> 
    <RegionName>California</RegionName> 
    <City>Mountain View</City> 
    <ZipPostalCode>94043</ZipPostalCode> 
    <Latitude>37.4192</Latitude> 
    <Longitude>-122.057</Longitude> 
    <Timezone>0</Timezone> 
    <Gmtoffset>0</Gmtoffset> 
    <Dstoffset>0</Dstoffset> 
</Response> 

Now after you have loaded this XML string into the simplexml_load_string() you can access the response's IP address like so.

$xml->IP;

simplexml_load_string() will transform well formed XML files into an object that you can manipulate. The only other thing I can say is go and try it out and play with it

EDIT:

Source http://www.php.net/manual/en/function.simplexml-load-string.php

like image 107
WarmWaffles Avatar answered Sep 29 '22 12:09

WarmWaffles