1

I am trying to bring in some API data to a directory in wordpress. The data I am trying to get is just crypto coin price, none of the other information but because its format is sort of nested (?) it doesnt seem to work.

{
  "bitcoin": {
    "usd": 16808.82 
  }
}

This is my code so far:

<?php
$handle = curl_init();
$url = get_post_meta($entity-\>post()-\>ID, '\_drts_field_004', true);

// Set the url
curl_setopt($handle, CURLOPT_URL, $url);
// Set the result output to be a string.
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);

$output = curl_exec($handle);
         
curl_close($handle);

$data = json_decode($output);
echo $output;
var_dump($data);

The results are:

{
    "bitcoin":{
        "usd":16833.02
        }
}    
object(stdClass)#10399 (1) { 
    ["bitcoin"]=> object(stdClass)#10492 (1) { 
        ["usd"]=> float(16833.02) 
        } 
}

In this example I am only after the 16833.02 I am trying to do this for lots of different coins, the "usd" will always be the same but the "bitcoin" will change when other coins. How can I echo only the number?

I have tried lots of variations of echo but cannot get it? Is it possible to do something like:

echo $data['bitcoin']['usd'];

but rather than bitcoin use * ? As in anything can be there?

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
Arctic
  • 13
  • 2
  • 1
    They are objects so us object notation `$data->bitcoin->usd` – RiggsFolly Jan 05 '23 at 12:44
  • 1
    Also, why the odd backslashes in the code – RiggsFolly Jan 05 '23 at 12:45
  • There is no wildcard array acess along the lines of `$data[*]['usd']`. If you only care about the value of the first member of the first member, but don't know what the keys are, you can use `echo current(current($data));`. ^_^ (You may want to use `json_encode($output, true);` to get an array instead of object.) – Markus AO Jan 05 '23 at 12:54
  • @MarkusAO you caught me out – Moshe Gross Jan 05 '23 at 12:56

1 Answers1

1

You can access the usd value by decoding the JSON to an array instead of an object like this

$data = json_decode($output, true);
$usd = current($data)['usd'];
Moshe Gross
  • 1,206
  • 1
  • 7
  • 14