【问题标题】:Using Curl to decode and echo a RESTful API response使用 Curl 解码和回显 RESTful API 响应
【发布时间】:2017-09-23 18:17:29
【问题描述】:

我试图简单地从这个 API 中获取并显示来自“Last”的数据: https://bittrex.com/api/v1.1/public/getticker?market=usdt-btc

这是我到目前为止所拥有的,但它没有返回任何东西。我不是经验丰富的开发人员,并且从几个不同的来源拼凑了这段代码。非常感谢任何帮助。

<?php

$service_url = 'https://bittrex.com/api/v1.1/public/getticker?market=usdt-btc';
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$curl_response = curl_exec($curl);
$decoded = json_decode($curl_response);

echo $decoded->Last;

?>

【问题讨论】:

    标签: php json curl restful-url


    【解决方案1】:

    您的代码有效。但是您必须更正确地检查 JSON 响应。如果你想得到“最后”,你首先必须得到结果。

    这是来自您的代码的 JSON 解码响应:

    object(stdClass)#1 (3) {
      ["success"]=>
      bool(true)
      ["message"]=>
      string(0) ""
      ["result"]=>
      object(stdClass)#2 (3) {
        ["Bid"]=>
        float(3760)
        ["Ask"]=>
        float(3765)
        ["Last"]=>
        float(3765)
      }
    }
    

    因此,您必须回显“$decoded->result->Last”

    【讨论】:

      【解决方案2】:

      $decoded 返回标准对象,所以你不能直接使用 echo 打印。如果你打印解码变量然后

      <?php
      $service_url = 'https://bittrex.com/api/v1.1/public/getticker?market=usdt-btc';
      $curl = curl_init($service_url);
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
      $curl_response = curl_exec($curl);
      $decoded = json_decode($curl_response);
      
      echo "<pre>";
      print_r($decoded);
      
       ?>
      

      结果:

       stdClass Object
      (
          [success] => 1
          [message] => 
          [result] => stdClass Object
              (
                  [Bid] => 3741.5957385
                  [Ask] => 3745
                  [Last] => 3745
              )
      
      )
      

      所以你可以访问

      echo $decoded->success; //return 1
      echo $decoded->result->Bid; //3741
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-21
        相关资源
        最近更新 更多