phpjsontripadvisor

How to decode json in php


I have this JSON data and want to decode it with PHP then insert into MySQL database:

{
  "data": [
    {
      "location_id": "5786213",
      "name": "Nirvana Lagoon Villas Suites & Spa",
      "distance": "0.0300528659549801",
      "bearing": "east",
      "address_obj": {
        "street1": "Goynuk Mahallesi, Baskomutan Ataturk Caddesi No: 141",
        "street2": null,
        "city": "Beldibi",
        "state": "Antalya Province",
        "country": "Turkey",
        "postalcode": null,
        "address_string": "Goynuk Mahallesi, Baskomutan Ataturk Caddesi No: 141, Beldibi, Kemer Turkey"
      }
    }
  ]
}

I am trying to decode with the following PHP code but I don't get any result:

 $url = "http://myurl"
 $jsondata = file_get_contents($url);
 $datatrip = json_decode($jsondata, true);

    $advisor_id = $datatrip['data']['location_id'];
    $advisor_name = $datatrip['data']['name'];  
    $distance = $datatrip['data']['distance'];
    $bearing = $datatrip['data']['bearing'];
    $street1 = $datatrip['data']['address_obj']['street1'];
    $street2 = $datatrip['data']['address_obj']['street2'];
    $city = $datatrip['data']['address_obj']['city'];
    $state = $datatrip['data']['address_obj']['state'];
    $country = $datatrip['data']['address_obj']['country'];
    $postalcode = $datatrip['data']['address_obj']['postalcode'];
    $address_string = $datatrip['data']['address_obj']['address_string'];

print_r() of the json_decode() result:

Array ( [data] => Array ( [0] => Array ( [location_id] => 5786213 [name] => Nirvana Lagoon Villas Suites & Spa [distance] => 0.0300528659549801 [bearing] => east [address_obj] => Array ( [street1] => Goynuk Mahallesi, Baskomutan Ataturk Caddesi No: 141 [street2] => [city] => Beldibi [state] => Antalya Province [country] => Turkey [postalcode] => [address_string] => Goynuk Mahallesi, Baskomutan Ataturk Caddesi No: 141, Beldibi, Kemer Turkey ) ) ) )

Is my method wrong to decode data?


Solution

  • You're decoding it fine but in your JSON the 'data' key is actually an array of objects (notice the [{...}]).

    So to access this you would need to specify the array key such as:

    $datatrip['data'][0]['address_obj']['postalcode'];
    

    Note the [0] in there.