【问题标题】:Parsing JSON data from a remote server从远程服务器解析 JSON 数据
【发布时间】:2023-03-16 05:02:01
【问题描述】:

我想知道是否有任何方法可以在 PHP 中制作解析器,从该站点获取值 https://btc-e.com/api/2/btc_usd/ticker 并将它们设置为 php 代码中的变量?

我看过一些 php 解析器,我发现的唯一的东西是可以在网站上回显所有信息的解析器。

【问题讨论】:

  • 如果您想知道 - 如果有解析的方法,那么 - 是的。那么你的问题是什么?做整个工作吗?添加具体问题描述
  • 这似乎是对我的 json 响应

标签: php json parsing bitcoin


【解决方案1】:

由于该 URL 返回 JSON 响应:

<?php

$content=file_get_contents("https://btc-e.com/api/2/btc_usd/ticker");
$data=json_decode($content);
//do whatever with $data now
?>

【讨论】:

  • 我已经尝试过了,但由于某种原因我得到一个错误 我得到这个错误 Fatal error: Cannot use object of type stdClass as array in C:\wamp3\www\DROPBOX\Dropbox\FTP\Test2.php on line 5
  • 默认情况下json_decode会给你一个对象,如果你必须使用它作为一个数组,那么你可以使用$data=json_decode($content,true);
【解决方案2】:

您可以使用file_get_contents 从URL 中获取数据并使用json_decode 来解析结果,因为您链接的站点返回一个JSON 数组,可以由php 原生解析。

例子:

$bitcoin = json_decode(file_get_contents("https://btc-e.com/api/2/btc_usd/ticker"), true);

在$bitcoin 变量中,您将拥有一个包含 JSON 字符串值的关联数组。

结果:

array(1) {
  ["ticker"]=>
  array(10) {
    ["high"]=>
    float(844.90002)
    ["low"]=>
    int(780)
    ["avg"]=>
    float(812.45001)
    ["vol"]=>
    float(13197445.40653)
    ["vol_cur"]=>
    float(16187.2271)
    ["last"]=>
    float(817.601)
    ["buy"]=>
    float(817.951)
    ["sell"]=>
    float(817.94)
    ["updated"]=>
    int(1389273192)
    ["server_time"]=>
    int(1389273194)
  }
}

【讨论】:

    【解决方案3】:

    该页面上的数据称为 Json (JavaScript Object Notation)(它不输出为 json mime 类型,但它的格式类似于 json)。
    如果您知道数据将是 json,则可以将其作为字符串从页面获取(例如使用 file_get_contents 函数)并使用 json_decode 函数将其解码为关联数组:

    <?php
    $dataFromPage = file_get_contents($url);
    $data = json_decode($dataFromPage, true);
    // Then just access the data from the assoc array like:
    echo $data['ticker']['high'];
    // or store it as you wish:
    $tickerHigh = $data['ticker']['high'];
    

    【讨论】:

    • 当我使用此代码时,我收到此错误致命错误:无法使用 stdClass 类型的对象作为第 5 行 C:\wamp3\www\DROPBOX\Dropbox\FTP\Test2.php 中的数组跨度>
    • @JVarhol 你确定你把json_decode($dataFromPage, true)函数的第二个参数设置为true吗?
    • 这是我的代码
    • @ProGM 我已将其设置为 true,我已将我的代码包含在上面,是否还有其他可能导致我出错的原因?
    • @JVarhol 检查stackoverflow.com/questions/6815520/… 。尝试转换为数组或使用 print_r($data);在 json_decode 之后检查该数据的值
    【解决方案4】:
    <?
    function GetJsonFeed($json_url)
    {
    $feed = file_get_contents($json_url);
    return json_decode($feed, true);
    }
    $LTC_USD = GetJsonFeed("https://btc-e.com/api/2/ltc_usd/ticker");
    $LTC_USD_HIGH = $LTC_USD["ticker"]["last"];
    
    $BTC_USD = GetJsonFeed("https://btc-e.com/api/2/btc_usd/ticker");
    $BTC_USD_HIGH = $BTC_USD["ticker"]["last"];
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-02
      • 2017-10-04
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多