Jan Jan - 1 month ago 11
PHP Question

getRemoteContents with CURL from JSON returns 0

Trying to get the value from 'price_usd' using get remote contents in PHP from the following JSON: https://api.coinmarketcap.com/v1/ticker/bitcoin/

It returns a 0 value. Can someone please explain what I am doing wrong here? Thanks! See code:

public function getUSD(){

$json = json_decode($this->getRemoteContents("https://api.coinmarketcap.com/v1/ticker/bitcoin/"), true);

return isset ($json['price_usd'])?($json['price_usd']):0;

}

public function getRemoteContents($url, $retries=5) {

$USER_AGENT = $_SERVER['HTTP_USER_AGENT'];

$result = "";

if (extension_loaded('curl') === true) {

$ch=curl_init();

curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);

curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->timeout);

curl_setopt($ch, CURLOPT_USERAGENT, $USER_AGENT);

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

curl_setopt($ch, CURLOPT_URL, $url);

$result = curl_exec($ch);

curl_close($ch);

unset($ch);

} else {

$options = array('http' => array('user_agent' => $USER_AGENT, 'timeout' => $this->timeout));

$context = stream_context_create($options);

$result = trim(file_get_contents($url,false, $context));

}

if (trim($result)=="") {

$retries-=1;

if ($retries >= 1) {

return $this->getRemoteContents($url,$retries);

}

}

return $result;

}


I think it has something to do with the return isset line?

Answer

You need to check for $json[0]['price_usd'].

Comments