正确转换货币

时间:2019-08-24 03:09:47

标签: php

我的默认货币为美元。

下面的类部分允许转换不同的货币,但是我的问题是,默认情况下,转换始终基于欧元。

如果选择该功能,如何更新该功能以使用美元作为默认值?

谢谢

EUR = 1(默认) 美元= 1.10 这种方法适用于任何货币

EUR = 0.9 USD = 1(默认) 这种方法行不通,因为默认情况下是美元,并且结果始终如上。

注意: $currenciesAdmin->getAll()以所有带有代码(EUR)和标题(Euro)的货币为例。

EUR的值始终为null,因为默认情况下转换基于EUR(有关值,请参见链接ecb.europa.eu)

public function getConvertCurrency()
{

  $currenciesAdmin = new CurrenciesAdmin();

  $XML = HTTP::getResponse([
    'url' => 'https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml'
  ]);

  if (empty($XML)) {
    throw new \Exception('Can not load currency rates from the European Central Bank website');
  }

  $currencies = [];

  foreach ($currenciesAdmin->getAll() as $c) {
    $currencies[$c['id']] = null;
  }

  $XML = new \SimpleXMLElement($XML);

  foreach ($XML->Cube->Cube->Cube as $rate) {
    if (array_key_exists((string)$rate['currency'], $currencies)) {
      $currencies[(string)$rate['currency']] = (float)$rate['rate'];
    }
  }

  foreach ($currencies as $code => $value) {
    if (!is_null($value)) {
      try {
        $this->db->save('currencies', [
          'value' => $value,
          'last_updated' => 'now()'
        ], [
          'code' => $code
        ]);
      } catch (\PDOException $e) {
        trigger_error($e->getMessage());
      }
    }
  }
}

1 个答案:

答案 0 :(得分:0)

通常,您会使用API​​,该API允许您选择基本货币并以这种方式进行转换。就是说,如果您需要使用此数据集,我相信以下方法可能对您有用:

$sourceCurrency = 'EUR'; // Your data source uses this as the base value
$defaultCurrency = 'USD'; // Read this from desired location

$currencies = [];
foreach ($currenciesAdmin->getAll() as $c) {
  $currencies[$c['id']] = null;
}

// This is a constant
$currencies[$sourceCurrency] = 1;

$XML = new \SimpleXMLElement($XML);

foreach ($XML->Cube->Cube->Cube as $rate) {
  $code = (string)$rate['currency'];
  if (array_key_exists($code, $currencies)) {
    $currencies[$code] = (float)$rate['rate'];
  }
}

if ($defaultCurrency !== $sourceCurrency) {
  // Conversion is required
  $convertedCurrencies = [];
  foreach (array_keys($currencies) as $code) {
    $convertedCurrencies[$code] = $currencies[$code] / $currencies[$defaultCurrency];
  }
  $currencies = $convertedCurrencies;
}

// Use $currencies as normal with the adjusted values

下面是一个交互式演示,其中包含可在浏览器中测试的JavaScript等效代码:

(() => {

  const currencyDropdown = document.querySelector('select');
  const selForm = document.querySelector('form');
  const sourceCurrency = 'EUR';
  let cachedData = null;
  const generateTable = async(first) => {
    const defaultCurrency = first ? sourceCurrency : currencyDropdown.options[currencyDropdown.selectedIndex].value;

    if (cachedData === null)
      cachedData = await fetch('https://cors-anywhere.herokuapp.com/https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml').then(r => r.text()).then(str => (new window.DOMParser()).parseFromString(str, "text/xml"));

    let currencies = Array.from(cachedData.querySelectorAll('Cube > Cube > Cube'))
      .reduce((a, c) => ({ ...a,
        [c.attributes.currency.value]: parseFloat(c.attributes.rate.value)
      }), {});
    currencies.EUR = 1;
    const currencyKeys = Object.keys(currencies).sort();
    currencyDropdown.innerHTML = currencyKeys.map(code => `<option${code === defaultCurrency ? ' selected' : ''}>${code}</option>`)
    if (sourceCurrency !== defaultCurrency) {
      const convertedCurrencies = currencyKeys.reduce((a, code) => ({
        ...a,
        [code]: currencies[code] / currencies[defaultCurrency],
      }), {});
      currencies = convertedCurrencies;
    }

    let tbl = document.querySelector('table');
    if (tbl !== null)
      tbl.remove();
    tbl = document.createElement('table');
    tbl.innerHTML = '<tr><th>code</th><th>value</th></tr>' +
      (currencyKeys.map(
        code => `<tr><td>${code}</td><td>${currencies[code]} ${defaultCurrency}</td></tr>`).join(''));
    document.body.appendChild(tbl);
    selForm.hidden = false;
  };
  selForm.addEventListener('submit', (e) => {
    e.preventDefault();

    generateTable(false);
  });
  generateTable(true);

})();
<form hidden>
  <label>
Default currency:
<select></select>
<input type="submit">
</label>
</form>
<table>
  <tr>
    <td>Loading&hellip;</td>
  </tr>
</table>