views:

145

answers:

3

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

+2  A: 

You really are better off using a XML parser to pull the information.

For example, this script will parse it into an array.

Regex really shouldn't be used to parse HTML or XML.

Aaron Harun
Please post an example!
xZerox
Updated for you. =)
Aaron Harun
+2  A: 

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

WarmWaffles
Or simply: `$xml = simplexml_load_file($url);`
salathe
Semantics ;-) it was the only real working example I had laying around
WarmWaffles
+1  A: 

If you really need to use regular expressions, then you should correct the one you are using. "|<CountryName>([^<]*)</CountryName>|i" would work better.

kiamlaluno
As reported from others, I would rather not use regular expressions for parsing HTML, XHTML, or XML if not in some particular cases. I had to quickly verify if the returned XML content contained a tag, and I used a regular expression; for other cases, it's much better to use SimpleXML, if the returned XML is not too big.
kiamlaluno