You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP调用blockchain.info接口提取BTC地址余额报错如何解决?

问题原因

第一次报错原因

  • json_decode()默认返回stdClass类型的对象,你使用数组方括号[]语法访问对象属性,就会触发「Cannot use object of type stdClass as array」的致命错误。

第二次报错原因

  • 修改为对象箭头->访问后仍然报错,是因为blockchain.info的余额接口返回结构为外层以查询的BTC地址为key,对应的值才是包含final_balance的对象,直接访问根对象的final_balance属性自然不存在。
  • 你第二版代码中给file_get_contents加的第二个参数true是无效设置,该参数作用是控制是否在系统include_path路径中查找文件,远程接口请求场景不需要设置。

接口返回的结构示例:

{
  "1BmXhLP1wkbDwgpPbdB57L7KrwBN9Q9Dkq": {
    "final_balance": 0,
    "n_tx": 0,
    "total_received": 0
  }
}
解决方法

两种常用写法任选其一即可:

写法1:保持对象访问方式

<?php
$btcAddress = "1BmXhLP1wkbDwgpPbdB57L7KrwBN9Q9Dkq";
$url1= "https://blockchain.info/balance?cors=true&active=".$btcAddress;
$value1 = file_get_contents($url1);
$data = json_decode($value1);
// 先通过BTC地址取到内层对象,再访问余额属性
$FinalBalance1 = $data->$btcAddress->final_balance;
echo $FinalBalance1;
?>

写法2:强制json_decode返回关联数组

给json_decode()添加第二个参数true,就会返回关联数组而非对象,更符合你第一版代码的编写习惯:

<?php
$btcAddress = "1BmXhLP1wkbDwgpPbdB57L7KrwBN9Q9Dkq";
$url1= "https://blockchain.info/balance?cors=true&active=".$btcAddress;
$value1 = file_get_contents($url1);
// 第二个参数设为true返回关联数组
$data = json_decode($value1, true);
$FinalBalance1 = $data[$btcAddress]["final_balance"];
echo $FinalBalance1;
?>

内容的提问来源于stack exchange,提问作者thebest man

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 02:06:04