Yesterday, I spent the afternoon playing around with different ways to display the price of Bitcoin in BrianLi.com’s page header. After I got everything working, I realized forcing the price of Bitcoin on readers is a terrible and stress-inducing idea from a UX perspective. Regardless, here’s the PHP code I used to make it happen.

<?php 
 
 /* CoinMarketCap API Endpoint */
 $url = 'https://api.coinmarketcap.com/v1/ticker/bitcoin/?convert=USD';
 $data = file_get_contents($url);
 /* Decode JSON array. */
 $priceInfo = json_decode($data);
 /* Put BTC price into btcPrice variable. */
 $btcPrice = $priceInfo[0]->price_usd;
 /* Set maximum number of decimal places to 2. */
 $btcPriceDec = number_format($btcPrice, 2);
 /* Display the price of Bitcoin. */
 echo 'BTCUSD = $' . $btcPriceDec; 

?>

If you’re using WordPress, I’d recommend sticking this code into a partial and calling it inside a specific template with the get_template_part function — keeps things nice and tidy.

This code snippet also works for other cryptocurrencies supported by CoinMarketCap’s API. To display the price of another cryptocurrency, just change the API endpoint URL and corresponding variables in the code. Here’s some code to display the price of ETH.

<?php 
 
 /* CoinMarketCap API Endpoint */
 $url = 'https://api.coinmarketcap.com/v1/ticker/ethereum/?convert=USD';
 $data = file_get_contents($url);
 /* Decode JSON array. */
 $priceInfo = json_decode($data);
 /* Put ETH price into ethPrice variable. */
 $ethPrice = $priceInfo[0]->price_usd;
 /* Set maximum number of decimal places to 2. */
 $ethPriceDec = number_format($ethPrice, 2);
 /* Display the price of Ether. */
 echo 'ETHUSD = $' . $ethPriceDec; 

?>

Feel free to @ me on Twitter