2016-01-21 31 views
1

我使用“新”谷歌货币计算器,而不是先例版本,现在我们有一个窗体,下拉菜单..等等,我需要的只是获得结果值。如何在使用谷歌货币api和php时只获得结果值?

这是我简单的PHP函数:

// 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 

返回一个形式..ect与结果:5 EUR = 5.4050 USD 如何获得唯一的:5.4050

谢谢。

回答

1
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" 
3
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"; 
}