How to get the default currency from the PHP Intl ( ICU library )

╄→гoц情女王★ 提交于 2019-11-30 07:37:44

问题


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:


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.



来源:https://stackoverflow.com/questions/8325002/how-to-get-the-default-currency-from-the-php-intl-icu-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!