Issue
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
Solution
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.
Answered By - Chris Strickland Answer Checked By - Marilyn (WPSolving Volunteer)