Reputation: 676
I'm using the "new" google currency calculator, and instead of the precedent version, now we have a form, with dropdown menus..etc, what i need is just to get the result value.
This is my simple php function :
// GOOGLE CURRENCY CONVERTER API
function converter_currency($amount, $from){
$result = file_get_contents('https://www.google.com/finance/converter?a='.$amount.'&from='.$from.'&to=USD');
print_r ($result);
// echo gettype($result); <== said that it's a string
}
converter_currency(5, 'EUR'); //converts 5euros to USD
That returns a form ..ect with the result : 5 EUR = 5.4050 USD
How to get only : 5.4050
?
Thank you.
Upvotes: 1
Views: 770
Reputation: 3746
function converter_currency($amount, $from, $to="USD"){
$result = file_get_contents('https://www.google.com/finance/converter?a='.$amount.'&from='.$from.'&to='.$to);
if($doc = @DomDocument::loadhtml($result)){
if($xpath=new DomXpath($doc)){
if($node = $xpath->query("//span")->item(0)){
$result = $node->nodeValue;
if($pos = strpos($result," ")){
return substr($result,0,$pos);
}
}
}
}
return "Error occured";
}
Upvotes: 3
Reputation: 36964
function converter_currency($amount, $from){
$result = file_get_contents('https://www.google.com/finance/converter?a='.$amount.'&from='.$from.'&to=USD');
preg_match('#\<span class=bld\>(.+?)\<\/span\>#s', $result, $finalData);
return $finalData[1];
}
echo converter_currency(5, 'EUR'); // 5.4125 USD
list($amount, $currency) = explode(' ', converter_currency(5, 'EUR'));
var_dump($amount, $currency); // string(6) "5.4125" string(3) "USD"
Upvotes: 1