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?

9 Answers 9


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

  $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 );

   <li>Price: <?=$usd_price ?> $ / <?=$bitcoin_price ?> BTC
  • 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: <?php echo "<ul> <li> Price: $usd_price $ / $bitcoin_price BTC </ul>"; ?> (the elephant image wouldn't be so bad if it was less massive)
    – mardlin
    Commented Aug 5, 2013 at 18:50
  • 1
    Enable "show errors" for php, and look whats wrong. php.net/manual/ru/errorfunc.configuration.php
    – user6203
    Commented Aug 5, 2013 at 19:39

May be useful psp(python) example:

import urllib2;     
import simplejson as json;     
j = json.loads(urllib2.urlopen("https://data.mtgox.com/api/2/BTCUSD/money/ticker").read());     

<%=str(j["data"]["last"]["value"]) %>

Or one command line:

# /usr/bin/python -c 'import urllib2; import simplejson as json; j = json.loads(urllib2.urlopen("https://data.mtgox.com/api/2/BTCUSD/money/ticker").read()); print str(j["data"]["last"]["value"]);'

Here is an example that retrieves the current current values from the json stream at mtgox (current, low, average, last, and now). It is written in python, but should be very easy to port it over to the language of your choice.


     #json is the standard python json parser
     #urllib2 is a webpage fetching library
import json     
import urllib2  

#The url that provides the raw json stream

#Open the url and turn it into an string containing the json

#Convert the json text into a json object

#Parse the desired values out of the json object
currentValue    = jsonObject['data']['high']['display']
lowValue        = jsonObject['data']['low']['display']
avgValue        = jsonObject['data']['avg']['display']
lastValue       = jsonObject['data']['last']['display']
nowValue        = jsonObject['data']['now']

#Sometimes your json is not a string,you will need to use json.load, not json.loads:

print jsonObject
print currentValue
print lowValue
print avgValue
print lastValue
print nowValue

Since Mt. Gox is down and the market is split, I would suggest using blockchain.info's API. I believe they combine different current market prices to make one average price. This is much more reliable than trusting one market only (see what happened to Mt. Gox). Also blockchain.info is a generally well trusted site.

To load the information in PHP use the file_get_contents() and json_decode() functions. Most of these functions are available in other high-end programming languages.


An older, maybe somewhat wiser me, answering my own question:

Here's some PHP to get the exchange rate.


$page = file_get_contents('https://bitpay.com/api/rates');
$my_array = json_decode($page, true);
$exchange_rate = $my_array[0]["rate"];      


I eventually found it easiest to do in javascript, since you're going to want to display the price as well.

Anywhere you have an element with `class="price", this will add the mBTC equivalent next to it. Tweak to your liking.

  $.getJSON('https://bitpay.com/api/rates', function(data){
    var rate = data[0].rate;

      var tex = $(this).text();
      var usdPrice = Number(tex.replace(/[^0-9.-]+/g,"")); 
      var mbtcPrice = 1000*usdPrice/rate;
      $(this).append("(&nbsp;~" + String(mbtcPrice.toFixed(0))+ "&nbsp;mBTC)");

Here's a bash command that gets the spot price from the Coinbase API (TM). It pipes the response to jq, which parses it and outputs the value(s) specified in the filter passed to it. -r strips the quotes from its output, which is passed to sed. sed processes the first 4 digits of this output, inserting a thousands comma and dollar sign. Note that it only works for 4-digit numbers (so will need to be modified shortly, replacing the '1' with a '2' ;-) The output redirection 2>/dev/null hides the curl curses interface:

curl --insecure https://coinbase.com/api/v1/prices/spot_rate 2>/dev/null | jq -r '.["amount"]' | sed 's/\([[:digit:]]\{1\}\)\([[:digit:]]\{3\}\)/\$\1,\2/g'

Hey I know this thread is 3 years old but anyway I used some of the code on this page to do my script because i couldn't make the code here to work...

import json
import urllib2




print jsonObject['bpi']['USD']['code']
print jsonObject['bpi']['USD']['rate']

Hope this will help future visitors.


As bitpay make some update, this code allows you to be already setup

<?php $url = "https://bitpay.com/api/rates";
$json = file_get_contents($url);
  $data = json_decode($json, TRUE);
for ($i=1; $i <20 ; $i++) { 
        $rate = $data[$i]["rate"];
    $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>
$url = "https://bitpay.com/api/rates";
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
$rate = $data[0]["rate"];
$rate1 = $data[1]["rate"];
$rate2 = $data[2]["rate"];
$rate145 = $data[145]["rate"];
BTC/USD: <?=$rate?>
BTC/EURO: <?=$rate1?>
BTC/GBP: <?=$rate2?>
BTC/VND : <?=$rate145?>

I edited the code from first answer and this one is work well

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.