Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 315
RoboTamer Avatar asked Dec 22 '22 05:12

RoboTamer


1 Answers

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.

like image 178
Gordon Avatar answered Dec 24 '22 00:12

Gordon