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

I am using PHP and would like to know how can I get the default currency for a locale through the internationalization extension (Wrapper for ICU library)?

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

 $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 that I need to install all the locales on Linux and solve the problem with Linux distributions. What would be the point of using Intl in the first place?

+4
source share
1 answer

After you set Locale to NumberFormatter, you can get 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 will give EUR, USD and JPY.

+10
source

Source: https://habr.com/ru/post/1383855/


All Articles