Last active
August 30, 2015 18:57
-
-
Save jesobreira/6f0d0e8854a4635eecbd to your computer and use it in GitHub Desktop.
How to get currency using Javascript or PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
@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); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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