I wrote the following php snippet to fetch the currency conversion rate from Yahoo Finance.
I'm using curl to fetch the data. Suppose, I want to convert from US dollars (USD) to Indian National Rupee (INR),then the url is http://in.finance.yahoo.com/currency/convert?amt=1&from=USD&to=INR&submit= and the Indian Rupee value is shown as 45.225. However,if i run my code, the value im getting is 452.25. Why this discrepancy?
<?php
$amount = $_GET['amount'];
$from = $_GET['from'];
$to = $_GET['to'];
$url = "http://in.finance.yahoo.com/currency/convert?amt=".$amount."&from=".$from."&to=".$to;
$handle = 开发者_如何学Pythoncurl_init($url);
curl_setopt ($handle, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($handle);
if(preg_match_all('/<td class="yfnc_tabledata1"><b>(?:[1-9]\d+|\d)(?:\.\d\d)?/',$data,$matches))
{
print_r($matches[0][1]);
}
else
{
echo "Not found !";
}
curl_close($handle);
?>
Is there something wrong with my regex?
Yahoo Finance (almost) certainly has a corresponding API, so you don't have to parse some random HTML for currency conversion.
Also, I would presume using something like Google's http://www.google.com/ig/calculator?q=1 EUR IN USD and parsing this response is much more stable than parsing Yahoo's HTML page.
You can get the rates in XML or JSON format using yahoo.finance.xchange open table:
Try it in YQL console
following code works. Give a try
$url = "http://www.xe.com/currencyconverter/convert/?
Amount=1&From=USD&To=INR";
$ch = curl_init();
$timeout = 0;
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_USERAGENT,
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$rawdata = curl_exec($ch);
curl_close($ch);
$data = explode('uccResultAmount', $rawdata);
@$data = explode('uccToCurrencyCode', $data[1]);
$amount = preg_replace('/[^0-9,.]/', '', $data[0]);
You can access Yahoo Currency via .csv files so it's much easier to parse those. Example: http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s='EURUSD'=x
And simple code:
function currencyImport($from,$to)
{
$url = 'http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s='. $from . $to .'=X';
$handle = @fopen($url, 'r');
if($handle)
{
$result = fgets($handle, 4096);
fclose($handle);
}
$currencyData = explode(',',$result);
return $currencyData[1];
}
精彩评论