Php – How to get JSON data with PHP


I am new with PHP and I am just trying to get one value from a JSON dictionary. This seems really simple (at least to me) but I am having trouble with it. I looked at the PHP documentation for JSON_decode and I also looked at "Parsing JSON data from a remote server" but that didn't do what I wanted. It returned the dictionary item I wanted as 0 then just spit out the JSON file. Then I looked at "get data from JSON with php" and that just returns nothing.

JSON Example

  "ask": 344.28,
  "bid": 343.89,
  "last": 343.97

First Try



echo "Decoded JSON:\n";
echo "$priceusd\n";
echo "Raw JSON:\n";
echo "$jsoncontent\n";

Second Try

 $result = iconv('UTF-16', 'UTF-8', $result);
 $json = json_decode($result);

 echo $json->last;

All I want is the value of one of the dictionary items in JSON at a URL.


Best Solution

Assuming $data contains what was returned from the server, you do:

$object = json_decode($data);
$last = $object->last;


$array = json_decode($data, true);
$last = $array['last'];

When you leave out the second argument to json_decode, it returns an object, and you access the part you want as an object property. If you give the second argument true, it returns an associative array, and you access the element using array notation.