user9055552
user9055552

Reputation:

How to get price from bitcoin to USD with api

Please help me how to get the price from bitcoin to USD with bitpay API. I wrote the following code, but I got USD to bitcoin price. I want bitcoin to USD price. Thanks!

<?php  
    $url = "https://bitpay.com/api/rates";

    $json = file_get_contents($url);
    $data = json_decode($json, TRUE);

    $rate = $data[1]["rate"];    
    $usd_price = 10;     # Let cost of elephant be 10$

    $bitcoin_price = round( $usd_price / $rate , 8 );
?>

Upvotes: 3

Views: 10134

Answers (1)

Professor Abronsius
Professor Abronsius

Reputation: 33813

Is this what you mean?

$url='https://bitpay.com/api/rates';
$json=json_decode( file_get_contents( $url ) );
$dollar=$btc=0;

foreach( $json as $obj ){
    if( $obj->code=='USD' )$btc=$obj->rate;
}

echo "1 bitcoin=\$" . $btc . "USD<br />";
$dollar=1 / $btc;
echo "10 dollars = " . round( $dollar * 10,8 )."BTC";

returns

1 bitcoin=$11485USD
10 dollars = 0.0008707BTC

Upvotes: 6

Related Questions