How to get the default currency from the PHP Intl

2020-02-10 08:38发布

I use PHP, and like to know how I can get the default currency for a locale via the Internationalization extension (Wrapper for the ICU library)?

Below is a script that explains, what and why. I need something to replace the getCurrCode() function with.

$accepted_currencies = array('USD','EUR');
$locale = Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']);
if( ! empty($locale)){
    Locale::setDefault($locale);
    $currency = getCurrCode();
    if( ! in_array($currency, $accepted_currencies)){
        $currency = 'USD';
    }
}else{
    Locale::setDefault('en_US');
}

$fmt = new NumberFormatter( $locale, NumberFormatter::CURRENCY );
$price = $fmt->formatCurrency(1234567.891234567890000, $currency);

I know, I could use setlocale(LC_MONETARY, $locale); but that means I have to install all the locale's on to Linux, and deal with the variation of the Linux distros. What would then be the point of using Intl at the first place?

1条回答
三岁会撩人
2楼-- · 2020-02-10 09:00

Once you set the Locale to the NumberFormatter, you can fetch the Currency Code with

$formatter = new NumberFormatter('de_DE', NumberFormatter::CURRENCY);
echo $formatter->getTextAttribute(NumberFormatter::CURRENCY_CODE);

$formatter = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
echo $formatter->getTextAttribute(NumberFormatter::CURRENCY_CODE);

$formatter = new NumberFormatter('ja_JP', NumberFormatter::CURRENCY);
echo $formatter->getTextAttribute(NumberFormatter::CURRENCY_CODE);

The above would give EUR, USD and JPY.

查看更多
登录 后发表回答