Get currency ISO 4217 code based on locale

橙三吉。 提交于 2019-12-12 20:36:10

问题


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;
    },
    []
);


来源:https://stackoverflow.com/questions/4299099/get-currency-iso-4217-code-based-on-locale

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!