duanaoyuan7202 2016-10-20 07:44
浏览 60
已采纳

来自JSON的CURL的getRemoteContents返回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?

  • 写回答

1条回答 默认 最新

  • doudou3935 2016-10-20 07:51
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算