如何通过使用PHP或Ajax通过API获得外汇汇率?

问题描述

我最近的项目需要PHP的外汇汇率API,其中60秒后需要更新,我还需要诸如黄金,白银等最新汇率的金属。因此,任何可以指导我使用PHP端点提供最新汇率的人。任何帮助将不胜感激。

解决方法

我会强烈推荐您CurrencyFreaks API。它提供多种语言的外币汇率端点,包括PHP和Ajax。它的主要特点是:

  • 数据每60秒更新一次。
  • 您可以更改“基本”货币。
  • 它提供了全球179种货币的货币汇率,包括货币,金属(金,银,钯,铂)和加密货币。
  • 端点支持的代码是Shell,Node.js,Java,Python, PHP,Ruby,JS,C#,Go,C,Swift。

以下是使用PHP的最新汇率端点:

setUrl('https://api.currencyfreaks.com/latest
    ?apikey=YOUR_APIKEY
    &base=GBP
    &symbols=EUR,USD,PKR,INR');
$request->setMethod(HTTP_Request2::METHOD_GET);
$request->setConfig(array(
  'follow_redirects' => TRUE
));
try {
  $response = $request->send();
  if ($response->getStatus() == 200) {
    echo $response->getBody();
  }
  else {
    echo 'Unexpected HTTP status: ' . $response->getStatus() . ' ' .
    $response->getReasonPhrase();
  }
}
catch(HTTP_Request2_Exception $e) {
  echo 'Error: ' . $e->getMessage();
}

对于Ajax:

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange",function() {
  if(this.readyState === 4) {
    console.log(this.responseText);
  }
});

xhr.open("GET","https://api.currencyfreaks.com/latest
    ?apikey=YOUR_APIKEY
    &base=GBP
    &symbols=EUR,INR");

xhr.send();

您还可以从以下其他语言获得外汇汇率终结点:https://currencyfreaks.com/documentation.html#Latest

我希望这个解决方案对您最近的项目有帮助。