-2

I am trying to access the fields of a JSON-File. The JSON look like:

{"ip":"83.215.135.170","location:"{"country":"AT","region":"Salzburg","city":"Salzburg","lat":47.8125,"lng":13.0504,"postalCode":"5020"

I want to access the latitude and longitude of this file. My current code looks like that:

    $data = json_decode($json);

    echo $data["location:"]["lat"];

I get the error that the index is undefined. Can anybody help me?

2 Answers2

1

You have a corupted JSON...here is the correct one

$json = '$json = '{"ip":"83.215.135.170","location":{"country":"AT","region":"Salzburg","city":"Salzburg","lat":47.8125,"lng":13.0504,"postalCode":"5020"}}';

With correct JSON you do this:

$decodedJson = json_decode($json,true);

And now you can do this:

echo $decodedJson["location"]["lat"]; // Prints 47.8125
JureW
  • 641
  • 1
  • 6
  • 15
0

if you want to access the fields like an array, you got to add "true" as a second parameter. https://www.php.net/manual/de/function.json-decode.php

$data = json_decode($json, true);

echo $data["location:"]["lat"];
Frederick Behrends
  • 3,075
  • 23
  • 47