【问题标题】:How to Convert Currency using google currency API in Php?如何在 PHP 中使用谷歌货币 API 转换货币?
【发布时间】:2018-06-19 06:36:10
【问题描述】:

我在 php 中通过使用 file_get_content 使用谷歌货币转换 API,但由于出现错误无法获取输出,所以如何在 PHP 中使用以下 API 转换任何货币。

<?php  
 function convertCurrency($amount, $from, $to)  
 {  
      $url = "http://www.google.com/finance/converter?a=$amount&from=$from&to=$to";  
      $data = file_get_contents($url);  
      preg_match("/<span class=bld>(.*)<\/span>/",$data, $converted);  
      return $converted[1];  
 }  
 echo convertCurrency(1500, 'USD', 'INR');  
 ?> 

出现这样的错误

Message: file_get_contents(http://www.google.com/finance/converter?a=1500&from=USD&to=INR): failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden

【问题讨论】:

  • 上面已经写了403 Forbidden,所以不行,你不能这样刮
  • @Ghost 那么如何做到这一点,请给我建议如何在 php 中解决这种货币转换
  • 你可以在这里查看这些答案,stackoverflow.com/questions/3139879/…
  • 尝试检查哪些符合您的要求

标签: php api currency


【解决方案1】:
function thmx_currency_convert($amount){
    $url = 'https://api.exchangerate-api.com/v4/latest/USD';
    $json = file_get_contents($url);
    $exp = json_decode($json);

    $convert = $exp->rates->USD;

    return $convert * $amount;
}
echo thmx_currency_convert(9);

【讨论】:

    【解决方案2】:

    有点晚了,但它可能对某些人有所帮助, 正如Benjamin所说的

    您不是在调用实际的 API,而是在抓取网页,这意味着:

    • 您很可能违反了 Google 的 TOS
    • 如果您过于频繁地获取此页面,您更有可能在某些时候受到速率限制(或被检测为滥用并被列入黑名单)

    代码片段

    $url = "https://www.google.com/search?q=INR+to+USD";//Change Accordingly
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    
    $result = curl_exec($ch);
    $data = explode("1 Indian Rupee = ",$result);//Change Accordingly
    $one_inr_rate_to_usd = (float) substr($data[1],0,7);
    

    【讨论】:

      【解决方案3】:

      几天前我已经回复了very similar question(代码和你的差不多)。

      我鼓励你阅读我的answer

      您不是在调用实际的 API,而是在抓取网页,这意味着:

      • 您很可能违反了 Google 的服务条款
      • 如果您过于频繁地获取此页面,您更有可能在某些时候受到速率限制(或被检测为滥用行为并被列入黑名单)

      这可能是你在这里遇到的。您很可能已被列入黑名单。

      解决方案:使用适当的 API,例如 OpenExchangeRates

      【讨论】:

        猜你喜欢
        • 2015-11-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多