Reputation: 369
I have the following php:
<?php
$json = file_get_contents('https://www.cryptonator.com/api/full/doge-usd');
$obj = json_decode($json);
echo $obj->ticker.price;
?>
This returns a blank page. Yet when I do:
echo $json;
I get the full JS:
{"ticker":{"base":"DOGE","target":"USD","price":"0.00013826","volume":"14555353.11203900","change":"-0.00000236","markets":[{"market":"Bleutrade","price":"0.00014400","volume":1.49328868},{"market":"Cex.io","price":"0.00013864","volume":6236157},{"market":"Comkort","price":"0.00014990","volume":412.40655758},{"market":"Cryptsy","price":"0.00013853","volume":382887.92442395},{"market":"Exmo","price":"0.00013800","volume":7932091.2389102},{"market":"Nix-e","price":"0.00011100","volume":539.10150086},{"market":"useCryptos","price":"0.00000305","volume":3263.94735765}]},"timestamp":1425854462,"success":true,"error":""}
I just want to create a variable that contains the value within the 'price' field.
Thanks.
Upvotes: 1
Views: 273
Reputation: 42885
The json_encode()
call returns a nested object. So you have to address the price attribute like that:
echo $obj->ticker->price;
The .
operator you coded is a string concatenation in php. That is not what you want. php tries to concatenate two strings, the first being an object of type stdClass for which no string conversion routine exists. That is why you get the error.
Upvotes: 1
Reputation: 2526
This is working and tested code:
<?php
$json = file_get_contents('https://www.cryptonator.com/api/full/doge-usd');
$obj = json_decode($json,true);
echo 'price: '.$obj['ticker']['price'];
?>
output: price: 0.00013833
Upvotes: 0
Reputation: 799
there are to ways to do this.
1) You can get the value like this
echo $obj->ticker->price;
2) You can convert the object into an associative array
$obj = json_decode($json, !!'assoc');
echo $obj["ticker"]["price"];
Upvotes: 1