Get currency ISO 4217 code based on locale

2019-07-21 22:42发布

问题:

Say, if I parse HTTP Accept-Language header with Locale::acceptFromHttp is there an easy and reliable way to get user's preferred currency based on this locale identifier? Like "USD" for "en-US".

I wish there was a way to do this with PHP intl extension but so far was unable to find my answer in the manual. I saw Zend Framework can do this with Zend_Currency but it's just too bloated for my particular software.

Any other libs or ways of achieving this? Since there must be a lot of locale identifiers a simple switch is a bit of overkill.

回答1:

You can do this in both PHP 4 and PHP 5 using setlocale() and localeconv():

$locale = Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']);
setlocale(LC_MONETARY, $locale);

print_r(localeconv());

Sample output:

Array
(
    [decimal_point] => .
    [thousands_sep] =>
    [int_curr_symbol] => EUR
    [currency_symbol] => €
    [mon_decimal_point] => ,
    [mon_thousands_sep] =>
    [positive_sign] =>
    [negative_sign] => -
    [int_frac_digits] => 2
    [frac_digits] => 2
    [p_cs_precedes] => 1
    [p_sep_by_space] => 1
    [n_cs_precedes] => 1
    [n_sep_by_space] => 1
    [p_sign_posn] => 1
    [n_sign_posn] => 2
    [grouping] => Array
        (
        )

    [mon_grouping] => Array
        (
            [0] => 3
            [1] => 3
        )

)

The ISO 4217 code is contained within the resulting array's int_curr_symbol key.



回答2:

A bit late but you can get it with \NumberFormatter:

<?php

$currencyPerLocale = array_reduce(
    \ResourceBundle::getLocales(''),
    function (array $currencies, string $locale) {
        $currencies[$locale] = \NumberFormatter::create(
            $locale,
            \NumberFormatter::CURRENCY
        )->getTextAttribute(\NumberFormatter::CURRENCY_CODE);

        return $currencies;
    },
    []
);


标签: php intl