谷歌货币转换器已更改其网址,但没有得到相同的结果


Google Currency Converter has changed its URL but not getting same result

我有以下代码(如下),使用的是iGoogle版本。

   $url = 'http://www.google.com/ig/calculator?hl=en&q=' . $amount . $from_Currency . '=?' . $to_Currency;
    $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('"', $rawdata);
    $data = explode(' ', $data[3]);
    $var = $data[0];

但是看过他们使用的是不同的URL:

  'http://www.google.com/finance/converter?hl=en&a=' . $amount . '&from=' . $from_Currency . '&to=USD';

但是简单地更改 url 不会返回我习惯的所需结果。

现在我得到的只是

 http://www.w3.org/TR/html4/strict.dtd

所以有没有人在这个最新的货币转换器 URL 上工作或有任何想法。 或使用 PHP 进行替换

感谢对问题进行了更深入的查找和重新措辞,找到了这篇文章。所以在某种程度上它是重复的。 但问题是:

需要 API 进行货币转换

我使用@hobailey答案进行临时修复,直到我可以将其更新到另一个版本或谷歌决定做一个适当的 api。

  $amount = urlencode($amount);
  $from_Currency = urlencode($from_Currency);
  $to_Currency = urlencode($to_Currency);
  $get = file_get_contents("https://www.google.com/finance/converter?a=$amount&from=$from_Currency&to=$to_Currency");
  $get = explode("<span class=bld>",$get);
  $get = explode("</span>",$get[1]);  
  $converted_amount = preg_replace("/[^0-9'.]/", null, $get[0]);

使用 XPath:

function currency($from, $to, $amount)
{
   $content = file_get_contents('https://www.google.com/finance/converter?a='.$amount.'&from='.$from.'&to='.$to);
   $doc = new DOMDocument;
   @$doc->loadHTML($content);
   $xpath = new DOMXpath($doc);
   $result = $xpath->query('//*[@id="currency_converter_result"]/span')->item(0)->nodeValue;
   return str_replace(' '.$to, '', $result);
}
echo currency('USD', 'EUR', 1); // returns 0.7216

我在这里创建了一个类,以更简单的方式连接到Google。

货币转换器-PHP

我希望它应该使某些方面变得更容易!

编辑:I才知道谷歌服务已于2013年11月关闭。

我将不得不改变它!

再次编辑:我已将Google Api更改为Yahoo Api,它工作得很好!

我找到了另一种解决方案。如果您的服务器IP无法使用谷歌服务,它也可以工作。

<?php
    $from_currency    = 'USD';
    $to_currency    = 'INR';
    $amount            = 1;
    $results = converCurrency($from_currency,$to_currency,$amount);
    $regularExpression     = '#'<span class=bld'>(.+?)'<'/span'>#s';
    preg_match($regularExpression, $results, $finalData);
    echo $finalData[0];
    function converCurrency($from,$to,$amount){
        $url = "http://www.google.com/finance/converter?a=$amount&from=$from&to=$to"; 
        $request = curl_init(); 
        $timeOut = 0; 
        curl_setopt ($request, CURLOPT_URL, $url); 
        curl_setopt ($request, CURLOPT_RETURNTRANSFER, 1); 
        curl_setopt ($request, CURLOPT_USERAGENT,"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)"); 
        curl_setopt ($request, CURLOPT_CONNECTTIMEOUT, $timeOut); 
        $response = curl_exec($request); 
        curl_close($request); 
        return $response;
    } 
?>

源参考步骤博客