4

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?

RoboTamer
  • 3,474
  • 2
  • 39
  • 43

1 Answers1

14

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.

Gordon
  • 312,688
  • 75
  • 539
  • 559
  • In Bhutan, there are 2 currencies (BTN and INR) but your sample code is returning only one (BTN) :( – Obaid Maroof Jul 24 '14 at 11:42
  • or for Cuba (es_CU), it only returns "CUP". Though in Cuba, there are two currencies i.e. "CUP" and "CUC" – Obaid Maroof Jul 24 '14 at 11:47
  • @ObaidMaroof please refer to the ICU documentation on how the handle these cases. – Gordon Jul 24 '14 at 13:03
  • For anyone who **only has the country code**, the NumberFormatter accepts English as a language for any country. So just use `en_` plus your country code. – Jonny Aug 03 '16 at 09:52