在 PHP 中获取货币符号

2022-01-12 00:00:00 currency formatting php

让我们从一段简单的代码开始,用 NumberFormatter 格式化货币:

Let's start with simple piece of code to format money with NumberFormatter:

$formatter = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
echo $formatter->formatCurrency(123456789, 'JPY');

打印:¥123,456,789.

如果你想格式化钱,这没关系.

This is ok if you want to format money.

但我想做的是获取给定货币 ISO 4217 代码(例如 JPY)的货币符号(例如 ¥).

But what I want to do is to get currency symbol (e.g. ¥) for given currency ISO 4217 code (e.g. JPY).

我的第一个猜测是尝试使用:

My first guess was to try using:

$formatter->getSymbol(NumberFormatter::CURRENCY_SYMBOL);

但这给出了构造函数 (en_US) 中给出的语言环境的货币符号,在我的例子中是 $.

But that gives currency symbol for locale given in constructor (en_US), $ in my case.

有没有办法在 PHP 中通过货币 ISO 4217 代码获取货币符号?

Is there a way to get currency symbol by currency ISO 4217 code in PHP?

推荐答案

我使用 https://github 实现了这个.com/symfony/Intl:

SymfonyComponentIntlIntl::getCurrencyBundle()->getCurrencySymbol('EUR')

返回

'€'.

Symfony 4.3 >

值得指出的是 SF4.3 及更高版本已弃用:

It's worth pointing out for SF4.3 and above this has been deprecated:

/**
 * Returns the bundle containing currency information.
 *
 * @return CurrencyBundleInterface The currency resource bundle
 *
 * @deprecated since Symfony 4.3, to be removed in 5.0. Use {@see Currencies} instead.
 */
public static function getCurrencyBundle(): CurrencyBundleInterface
{

所以,你可以这样做:

use SymfonyComponentIntlCurrencies;
echo Currencies::getSymbol('AUD'); 

相关文章