0

here i got this below data with this

$location = file_get_contents('http://freegeoip.net/json/'.$_SERVER['REMOTE_ADDR']);

and $location contains :

{
      "ip": "77.99.179.98",
      "country_code": "GB",
      "country_name": "United Kingdom",
      "region_code": "H9",
      "region_name": "London, City of",
      "city": "London",
      "zipcode": "",
      "latitude": 51.5142,
      "longitude": -0.0931,
      "metro_code": "",
      "areacode": ""

}

have received this data. but am not getting how to pink country_name and region_name from this?

Satish Sharma
  • 9,547
  • 6
  • 29
  • 51
mssjdb
  • 15
  • 1
  • 5
  • Did you catch that data in a variable? Then there will be solution with string position function.$location= what a directory or the data after executing your code? – Muhammad Ashikuzzaman Jul 26 '14 at 11:25
  • possible duplicate of [How to convert JSON string to array](http://stackoverflow.com/questions/7511821/how-to-convert-json-string-to-array) – Kevin Jul 26 '14 at 13:32

5 Answers5

0

you can user jsone_decode like this

    $output_string = '{
      "ip": "77.99.179.98",
      "country_code": "GB",
      "country_name": "United Kingdom",
      "region_code": "H9",
      "region_name": "London, City of",
      "city": "London",
      "zipcode": "",
      "latitude": 51.5142,
      "longitude": -0.0931,
      "metro_code": "",
      "areacode": ""

}';

$arr = json_decode($output_string, true);
echo "Country  Name :".$arr['country_name'];
echo "\nRegion  Name :".$arr['region_name'];

see Working Demo

Satish Sharma
  • 9,547
  • 6
  • 29
  • 51
0

try this

$obj = json_decode($location, true);

then try to get the object

echo $obj['country_name'];
Shah Rukh
  • 3,046
  • 2
  • 19
  • 27
0
$locationArray = json_decode($location, true);
echo $locationArray['country_name'];
Lorenz Meyer
  • 19,166
  • 22
  • 75
  • 121
0

This works:

$arr = json_decode('{
      "ip": "77.99.179.98",
      "country_code": "GB",
      "country_name": "United Kingdom",
      "region_code": "H9",
      "region_name": "London, City of",
      "city": "London",
      "zipcode": "",
      "latitude": 51.5142,
      "longitude": -0.0931,
      "metro_code": "",
      "areacode": ""

}');

echo $arr->country_code . ", " . $arr->country_name;

Add a true argument to json_decode($json_string, true) to return an array instead of an object as above.

$arr = json_decode('{
      "ip": "77.99.179.98",
      "country_code": "GB",
      "country_name": "United Kingdom",
      "region_code": "H9",
      "region_name": "London, City of",
      "city": "London",
      "zipcode": "",
      "latitude": 51.5142,
      "longitude": -0.0931,
      "metro_code": "",
      "areacode": ""

}', true);

echo $arr['country_code'] . ", " . $arr['country_name'];
IROEGBU
  • 948
  • 16
  • 33
-2

Use $location->country_code; it will give you country code.

GTS Soft.
  • 187
  • 4