【问题标题】:getRemoteContents with CURL from JSON returns 0来自 JSON 的带有 CURL 的 getRemoteContents 返回 0
【发布时间】:2016-10-20 07:44:44
【问题描述】:

尝试使用从以下 JSON 获取 PHP 中的远程内容从“price_usd”获取值:https://api.coinmarketcap.com/v1/ticker/bitcoin/

它返回一个 0 值。有人可以解释我在这里做错了什么吗?谢谢!见代码:

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;

    } 

我认为这与 return isset 行有关?

【问题讨论】:

    标签: php arrays json curl


    【解决方案1】:

    您需要检查$json[0]['price_usd']

    【讨论】:

      猜你喜欢
      • 2016-06-12
      • 2015-07-17
      • 2016-06-05
      • 1970-01-01
      • 2016-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-21
      相关资源
      最近更新 更多