Christian Heilmann

Posts Tagged ‘lackofapi’

Currency conversion API on a shoestring

Saturday, June 21st, 2008

Someone just came to our table at Mashed08 and asked if Yahoo! offers a currency conversion API. We don’t, but a few lines of PHP allows you to get the information from the Yahoo finance site:


function convert($from,$to){
$url= ‘http://finance.yahoo.com/currency/convert?amt=1&from=’.$from.’&to=’.$to.’&submit=Convert’;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$feed = curl_exec($ch);
curl_close($ch);
preg_match_all(“/tabledata1”>([^<]+)/”,$feed,$cells);
return $cells[1][1];
}

echo convert(‘USD’,’GBP’);

There’s a whole list of currency codes available on oanda.

A few more lines turns this into a JSON API:


header(‘Content-type:text/javascript’);
$from = $_GET[‘from’];
$to = $_GET[‘to’];
$callback = $_GET[‘callback’];
if(preg_match(“/[A-Z|a-z]{3}/”,$to) && preg_match(“/[A-Z|a-z]{3}/”,$from)){
$to = strToUpper($to);
$from = strToUpper($from);
$url= ‘http://finance.yahoo.com/currency/convert?’ .
‘amt=1&from=’.$from.’&to=’.$to.’&submit=Convert’;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$feed = curl_exec($ch);
curl_close($ch);
preg_match_all(“/tabledata1”>([^<]+)/”,$feed,$cells);
if(is_numeric($cells[1][1])){
$out = ‘{“from”:”’.$from.’”,”to”:”’.$to.’”,”factor”:”’.$cells[1][1].’”}’;
} else {
$out = ‘{error not convert currencies, are you sure about the names?”}’;
}

} else {
$out = ‘{error Currency format, must be three letters”}’;
}

if(isset($callback)){
if(preg_match(“/[a-z|A-Z|_|-|$|0-9|.]/”,$callback)){
$out = $callback.’(‘.$out.’)’;
} else {
$out = ‘{error callback method name”}’;
}

}
echo $out;

You have several parameters:

  • from (mandatory): three letter currency code (upper or lower case)
  • to (mandatory): three letter currency code (upper or lower case)
  • callback (optional): the name of the callback method that should be wrapped around the resulting object

If something goes wrong, the API will return an object with an error property, otherwise you’ll get an object with three properties:

  • from: the original currency
  • to: the target currency
  • factor: the conversion factor

Say you store this as convert.php somewhere, then you could do the following:




This is a terrible dirty hack and if Yahoo finance ever changes their HTML (and they will), this will cease to work.