Guille Acosta
Guille Acosta

Reputation: 2222

Can't retrieve value of JSON Object attr after json_encode in PHP

I'm not able to get the value of the image attribute in this (apparently valid) JSON object:

echo var_dump($result);

array(1) {
  ["images"]=>
  array(1) {
    [0]=>
    array(1) {
      ["src"]=>
      string(112) "http://staticf5a.diaadia.info/sites/default/files/styles/landscape_310_155/public/nota_periodistica/taxis_13.jpg"
    }
  }
}

$jsonResult = json_encode($result); //result is an array of arrays
echo $jsonResult;

{"images":[{"src":"http:\/\/staticf5a.diaadia.info\/sites\/default\/files\/styles\/landscape_310_155\/public\/nota_periodistica\/taxis_13.jpg"}]}

echo $jsonResult->images; //show nothing

This snippet was working few days ago, and logs (ini_set('display_errors', '0');) don't show anything related.

Upvotes: 0

Views: 776

Answers (2)

Elentriel
Elentriel

Reputation: 1237

You are trying to get property from a string here. json_encode() returns the json representation of an object as a string. That string you can turn into an actuall object with json_decode()

Upvotes: 0

jedrzej.kurylo
jedrzej.kurylo

Reputation: 40919

After encoding, $jsonResult is just a string and you won't be able to access any elements of encoded JSON without decoding it first.

Have a look at PHP's ``json_decode'' function: http://php.net/manual/pl/function.json-decode.php

It will convert the JSON back to associative array or object.

Anyway, I have no idea why you encode the associative array as JSON and try to access images there instead of just taking it from the array itself.

Upvotes: 3

Related Questions