Home > Blockchain >  How to extract address balance
How to extract address balance

Time:10-05

I'm trying to extract BTC address while checking it via blockchain.info

My code:

<?php

$url1= "https://blockchain.info/balance?cors=true&active=1BmXhLP1wkbDwgpPbdB57L7KrwBN9Q9Dkq";
$value1 = file_get_contents($url1);
$data = json_decode($value1);
$FinalBalance1 = $data["final_balance"];
echo $FinalBalance1;

?>

I'm getting this error:

PHP Fatal error:  Uncaught Error: Cannot use object of type stdClass as array in C:\laragon\www\balancechecker\test.php:5
Stack trace:
#0 {main}
  thrown in C:\laragon\www\balancechecker\test.php on line 5

Fatal error: Uncaught Error: Cannot use object of type stdClass as array in C:\laragon\www\balancechecker\test.php:5
Stack trace:
#0 {main}
  thrown in C:\laragon\www\balancechecker\test.php on line 5

What I'm missing? I'm just learning please bear with me. Thank you

Another shot:

<?php
$url1= "https://blockchain.info/balance?cors=true&active=1BmXhLP1wkbDwgpPbdB57L7KrwBN9Q9Dkq";
$value1 = file_get_contents($url1,true);
$data = json_decode($value1);
$FinalBalance1 = $data->final_balance;
echo $FinalBalance1;

?>

Error I'm getting:

PHP Notice:  Undefined property: stdClass::$final_balance

CodePudding user response:

Try to set the associative parameter. Without this parameter set to true, json_decode($value1) will return an object.

Alternatively you could change $data["final_balance"] to $data->final_balance. Depending on what you prefer.

Edit:

It seems that you use the result wrong. Visiting the URL via browser shows, that the data has the key 1BmXhLP1wkbDwgpPbdB57L7KrwBN9Q9Dkq.

A fixed Version could be:

$url1= "https://blockchain.info/balance?cors=true&active=1BmXhLP1wkbDwgpPbdB57L7KrwBN9Q9Dkq";
$value1 = file_get_contents($url1,true);
$data = json_decode($value1, true);
$FinalBalance1 = $data['1BmXhLP1wkbDwgpPbdB57L7KrwBN9Q9Dkq']['final_balance'];
echo $FinalBalance1;

Edit:

A version with btc address as parameter.

$address = "1BmXhLP1wkbDwgpPbdB57L7KrwBN9Q9Dkq";
$url1= "https://blockchain.info/balance?cors=true&active=".$address;
$value1 = file_get_contents($url1,true);
$data = json_decode($value1, true); # <- note the second parameter
$FinalBalance1 = $data[$address]['final_balance'];
echo $FinalBalance1;
  •  Tags:  
  • php
  • Related