6

This is a pretty classic programming question, but I think it is a very common one for the Bitcoin community, and would be helpful to have the code publicly available.

My preference is for a php script.


Bitpay publishes it's exchange rates here: https://bitpay.com/api/rates

If an item is $10 USD, how would I do the following?

1) extract the BTC/USD exchange rate from the array at this URL
2) Define the price, then divide by the exchange rate
3) Display the BTC price in an HTML page?

spuder
  • 231
  • 2
  • 9
mardlin
  • 406
  • 1
  • 4
  • 11

9 Answers9

10

Save the code to a PHP file in the web directory:

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

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

  $rate = $data[2]["rate"];   //$data[1] is outdated now, they have updated their json order. This new number 2 now fetches USD price. 
  $usd_price = 10;     # Let cost of elephant be 10$
  $bitcoin_price = round( $usd_price / $rate , 8 );
?>

<ul>
   <li>Price: <?=$usd_price ?> $ / <?=$bitcoin_price ?> BTC
</ul>
  • 1
    This didn't work for me, instead it simply output "Price $/BTC" I don't know PHP well, but some googling led me to replace the last three lines with:
  • Price: $usd_price $ / $bitcoin_price BTC "; ?> (the elephant image wouldn't be so bad if it was less massive)
  • – mardlin Aug 05 '13 at 18:50
  • 1
    Enable "show errors" for php, and look whats wrong. http://php.net/manual/ru/errorfunc.configuration.php –  Aug 05 '13 at 19:39