Home > Mobile >  Error while trying to decode a json response from CURL request
Error while trying to decode a json response from CURL request

Time:02-23

I'm trying to decode a json response that looks like this and get only the value for USD

{"data":{"currency":"TRX","rates":{"AED":"0.22938983227","USD":"0.06245299"}}}
    $url = "https://api.coinbase.com/v2/exchange-rates?currency=TRX";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // On dev server only!

$result = curl_exec($ch);
$json = json_decode($result, true);

echo $json['USD'];

But I keep getting this error message - Notice: Undefined index: USD in C:\xampp\htdocs*****.php on line 19

CodePudding user response:

I think what you expect the array to look like and what it actually looks like are different. $json['USD'] doesn't exist, but $json['data']['rates']['USD'] does.

You can use print_r on the array to view it:

echo "<pre>"; print_r($json); echo "</pre>";

or you could also use a json formatter like http://www.bodurov.com/JsonFormatter/, which I personally use all the time.

CodePudding user response:

You can replace:

$json = json_decode($result, true);

to:

$json = json_decode($result);

and print you data in object oriented mode like this:

echo $json->data->currency . ' > '. $json->data->rates->USD;

I hope to be helpful

  • Related