0

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

7
  • Would var_dump($json) and make sure it is indexed as expected. Note the data key. Commented Feb 22, 2022 at 21:49
  • No, but this key exists: $json['data']['rates']['USD']; I think what you expect the array to look like and what it really looks like are different. Use print_r on the array to see it. Something like: echo "<pre>"; print_r($json); echo "</pre>"; Commented Feb 22, 2022 at 21:50
  • Also, try putting the json response into a json formatter like bodurov.com/JsonFormatter to see it easier. Commented Feb 22, 2022 at 21:51
  • $json['data']['rates']['USD'] Commented Feb 22, 2022 at 21:51
  • @ChrisStrickland, It worked, thanks for the help, I really do appreciate it Commented Feb 22, 2022 at 21:56

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.