Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top