User Rating: 0 / 5

Star inactiveStar inactiveStar inactiveStar inactiveStar inactive
 

After looking at the API at BitcoinCharts.com, i saw that it would be rather simple to return the weighted prices of bitcoin with PHP and JSON. In this tutorial, we are going to return the 7 day, 30 day and 24 hour bitcoin averages. Because BitcoinCharts.com asks not to query more than once every 15 minutes, we are going to cache the json file for 1 hour on the site.

<?
	$cache_filename = "bitcoin_weighted_prices.json";
	if (file_exists($cache_filename) && filemtime($cache_filename)>=strtotime("-1 hour"))
	{
		$content = file_get_contents($cache_filename);
	}
	else
	{
		$url = "http://api.bitcoincharts.com/v1/weighted_prices.json";
		$content = @file_get_contents($url);
		if (!$content) exit("Error retrieving JSON file from BitcoinCharts.com");
		file_put_contents($cache_filename, $content);
	}
	$json = json_decode($content, true);
	if (!$json) exit("JSON error.)";
	echo "<b>7 day weighted:</b> $" .$json["USD"]["7d"] ."<br />";
	echo "<b>30 day weighted:</b> $" .$json["USD"]["30d"] ."<br />";
	echo "<b>24 hour weighted:</b> $" .$json["USD"]["24h"] ."<br />";
?>

 Line 2 is simple making a variable with the name of the cache file that is going to be stored on the server. Line 3 checks to see if to see if the file exists, then checks to see if the file is less than a hour old, if both are TRUE, then line 5 will retrieve information in the cache file and store it in the variable $content.

Posted: 11 months 1 week ago by admin #174
admin's Avatar
Should have an article here soon showing how to use this with Joomla and create a module.


Donate Bitcoins