I have been having a hard time retrieving eth Value from a Json url for a while now, it keeps returning the error “Undefined offset: 0” as easy as it may be to anyone giving the answer, please consider that i am a learner and upcoming. My code below
JavaScript
x
$ethjs = "https://api.coingecko.com/api/v3/simple/token_price/ethereum?contract_addresses=0xdac17f958d2ee523a2206206994597c13d831ec7&vs_currencies=eth";
$ejson = file_get_contents($ethjs);
$ejson = json_decode($ejson, true);
$one_eth = $ejson[0]->eth;
Advertisement
Answer
The response from the url is something like
JavaScript
// https://api.coingecko.com/api/v3/simple/token_price/ethereum?contract_addresses=0xdac17f958d2ee523a2206206994597c13d831ec7&vs_currencies=eth
{
"0xdac17f958d2ee523a2206206994597c13d831ec7": {
"eth": 0.0003859
}
}
Few things from above output
- There’s no [0] as you are trying to extract
- since this seems to be PHP which supports heterogeneous arrays, you need to access it via value of the
contract_address
parameter passed in url since that is thekey
in the result object.
Putting it altogether.
JavaScript
$ethjs = "https://api.coingecko.com/api/v3/simple/token_price/ethereum?contract_addresses=0xdac17f958d2ee523a2206206994597c13d831ec7&vs_currencies=eth";
$ejson = file_get_contents($ethjs);
$ejson = json_decode($ejson, true);
$one_eth = $ejson['0xdac17f958d2ee523a2206206994597c13d831ec7']['eth'];
echo $one_eth;