有没有更好的方法来获取PHP的货币汇率? [英] Is there any better way to get Currency Exchange Rate in PHP?

查看:359
本文介绍了有没有更好的方法来获取PHP的货币汇率?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

带有以下代码的货币汇率有时有效,有时无效,并且根本不可靠。有没有更好的方法来获取PHP中的货币汇率?

Currency Exchange Rate with below code is working sometimes and not working sometimes and not at all reliable. Is there any better way to get Currency Exchange Rate in PHP?

public function getJPYtoUSDExchangeRate(){
    $from    = 'JPY';
    $to    = 'USD';
    $amount  = 1;
    $data = file_get_contents("https://finance.google.com/finance/converter?a=$amount&from=$from&to=$to");
    preg_match("/<span class=bld>(.*)<\/span>/",$data, $converted);
    $converted = preg_replace("/[^0-9.]/", "", $converted[1][0]);
    return number_format(round($converted, 3),2);
}


推荐答案

您遇到了几个问题:


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


    • 您最有可能违反Google的服务条款

    • 您更有可能在以下位置受到速率限制(或被检测为滥用并被列入黑名单)某些情况下,如果您经常访问此页面

    • 您将依赖于网页的HTML结构所做的任何更改

    您应该做什么:


    • 从合法帐户中加载汇率feed或API

    • 定期加载它们(例如,通过cron作业)并将其保存到本地数据库,将被使用d执行货币转换

    • load exchange rates from a legitimate feed or API
    • load them on a regular basis (via a cron job for example) and save them to a local database, that will be used to perform currency conversions

    这样,即使API调用失败,您仍然可以使用稍微过时的汇率,在大多数情况下,失败比失败要好。

    This way, even if an API call fails, you still have access to a slightly outdated exchange rate, which is better than a failure in most cases.

    有很多提供此服务的API,无论是否免费。

    There are plenty of APIs, free or not, that offer this service.

    我知道的一个很好的来源是欧洲中央银行银行,该银行提供了已经存在多年的 XML提要。提供相对于 EUR 的32种货币的汇率。

    A good source I know of is the European Central Bank, who provides an XML feed that's been there for years and provides exchange rates for 32 currencies relative to EUR.

    OpenExchangeRates 还提供了一个免费计划,每月限制1,000个请求,这足以每小时刷新一次费率。它提供了170种货币的汇率,相对于 USD

    OpenExchangeRates also offers a free plan with a limit of 1,000 requests per month, which is enough to refresh rates every hour. It provides exchange rates for 170 currencies, relative to USD.

    无论您选择哪种提要,都需要对其进行解析(如果是XML)或 json_decode()它(如果是JSON) )并将值存储在数据库中。理想情况下,设置一个cron作业以每天甚至每小时运行一次导入脚本。

    Whichever feed you choose, you need to parse it (if XML) or json_decode() it (if JSON) and store the values in your database. Ideally, set up a cron job to run your import script daily or even hourly.

    实际的解析和导入步骤不在此问题的范围内,但是我们假设保存记录的简单MySQL表:

    The actual parsing and importing steps are outside the scope of this question, but let's assume a simple MySQL table that holds the records:

    CREATE TABLE exchange_rate(
      target_currency CHAR(3) COLLATE ascii_bin NOT NULL PRIMARY KEY,
      exchange_rate DOUBLE NOT NULL
    );
    



    如何根据相对于一种货币的汇率正确处理货币转换?



    这是我最近回答的问题。上面的供稿可为您提供将基础货币( EUR USD )转换为另一种货币的费率,但不提供您将了解如何在两种任意货币之间进行转换。我建议您使用适当的库来为您处理这些转换,例如 brick / money -免责声明:我是作者

    How to properly handle currency conversions based on rates relative to a single currency?

    This is a question I've answered recently. The feeds above give you rates to convert the base currency (EUR or USD) to another currency, but do not give you a clue on how to convert between two arbitrary currencies. I would suggest you use a proper library that handles these conversions for you, such as brick/money - disclaimer: I'm the author.

    这里是如何配置它以加载上表中的汇率:

    Here is how you would configure it to load your exchange rates from the table above:

    use Brick\Money\CurrencyConverter;
    use Brick\Money\ExchangeRateProvider\PDOProvider;
    use Brick\Money\ExchangeRateProvider\PDOProviderConfiguration;
    use Brick\Money\ExchangeRateProvider\BaseCurrencyProvider;
    
    // set to whatever your rates are relative to
    $baseCurrency = 'USD';
    
    // use your own credentials, or re-use your existing PDO connection
    $pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '');
    
    $configuration = new PDOProviderConfiguration();
    
    $configuration->tableName                = 'exchange_rate';
    $configuration->exchangeRateColumnName   = 'exchange_rate';
    $configuration->targetCurrencyColumnName = 'target_currency';
    $configuration->sourceCurrencyCode       = $baseCurrency;
    
    // this provider loads exchange rates from your database
    $provider = new PDOProvider($pdo, $configuration);
    
    // this provider calculates exchange rates relative to the base currency
    $provider = new BaseCurrencyProvider($provider, $baseCurrency);
    
    // this currency converter can now handle any currency pair
    $converter = new CurrencyConverter($provider);
    

    使用方式:

    use Brick\Math\RoundingMode;
    use Brick\Money\Money;
    
    $money = Money::of(10, 'EUR'); // EUR 10.00
    $converter->convert($money, 'CAD', RoundingMode::DOWN); // CAD 15.27
    

    这篇关于有没有更好的方法来获取PHP的货币汇率?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆