Skip to content

Instantly share code, notes, and snippets.

@jesobreira
Last active August 30, 2015 18:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jesobreira/6f0d0e8854a4635eecbd to your computer and use it in GitHub Desktop.
Save jesobreira/6f0d0e8854a4635eecbd to your computer and use it in GitHub Desktop.
How to get currency using Javascript or PHP
/*
@author Jefrey S. Santos <github.com/jesobreira>
*/
function currency(icoin1, icoin2, value, callback) {
if(typeof value == 'undefined') value = 1;
icoin1 = icoin1.toUpperCase();
icoin2 = icoin2.toUpperCase();
value = parseFloat(value);
var url = 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20%3D%20%27'+icoin1+icoin2+'%27&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=';
$.getJSON(url, function(data) {
theval = parseFloat((data.query.results.rate.Rate)*value);
callback(theval);
}, function() {
console.error('error fetching currency url');
})
}
// Example:
currency('btc', 'usd', 2, function(val) {
alert("2 bitcoins are the same as US$ "+val);
});
<?php
/*
@author Jefrey S. Santos <github.com/jesobreira>
*/
function currency($icoin2, $icoin1, $value=1) {
$coin1 = strtoupper($icoin1);
$coin2 = strtoupper($icoin2);
$coin1 = preg_replace("/[^A-Z{3}]/", null, $coin1);
$coin2 = preg_replace("/[^A-Z{3}]/", null, $coin2);
$currency = @file_get_contents('http://download.finance.yahoo.com/d/quotes.csv?s='.$coin2.$coin1.'=X&f=sl1d1t1ba&e=.csv');
$currency = explode(",", $currency);
$value = (float)($currency[1]*$value);
return $value;
}
$val = currency('btc', 'brl', 2);
echo "2 bitcoins are the same as US$ ".$val;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment