PHP - print GeoIP array

271 views Asked by At

I fiddling around with freegeoip.net,trying to get some more info for the IP of my visitors. I can successfully retrieve array information for the user's IP, but cant seem to break the array apart and get individual variables for IP, City, Country Code, etc.

Array Result:

Array ( [ip] => 77.99.179.98 [country_code] => GB [country_name] => United Kingdom [region_code] => ENG [region_name] => England [city] => Gloucester [zip_code] => GL1 [time_zone] => Europe/London [latitude] => 51.8333 [longitude] => -2.25 [metro_code] => 0 ) 

PHP

<?php
$ip = "77.99.179.98";

$geoip = json_decode(file_get_contents('http://freegeoip.net/json/'.$ip), true);
print_r($geoip);

foreach ($geoip as $result) {
    echo $result['ip']."<br>";
}

?>

EDIT: I now receive a Warning: Illegal string offset 'ip' in ... on line 9 error, but do get the first digit of the IP Address returned... wth?

1

There are 1 answers

0
Armitage2k On

At last!

<?php
$ip = "77.99.179.98";

$ip_data = file_get_contents('http://freegeoip.net/json/'.$ip);
$data = json_decode($ip_data);

print_r($data);

echo "<br><br>";

echo htmlspecialchars($data->country_name);

?>