Get currency symbol in PHP

前端 未结 8 818
春和景丽
春和景丽 2020-12-14 00:07

Let\'s start with simple piece of code to format money with NumberFormatter:

$formatter = new NumberFormatter(\'en_US\', NumberFormatter::CURREN         


        
相关标签:
8条回答
  • 2020-12-14 00:44

    You can use Symfony Intl Component

    Install it via composer using composer require symfony/intl

    Then get the HTML symbol with the following

    use Symfony\Component\Intl\Currencies;
    \Locale::setDefault('en');
    $symbol = Currencies::getSymbol('INR'); // => '₹'
    echo $symbol;
    
    0 讨论(0)
  • 2020-12-14 00:52

    Cryptic has a good answer, but there is a simpler way to do it:

    preg_replace('#[a-z0-9.]*#i', '', $formatter->formatCurrency('0', $currency))
    

    This is a nice simple inline solution that doesn't require declaring another function, however it also doesn't properly handle all cases - i.e. currencies where letters are part of the output. But for distinguishing between e.g. $ and £, it works fine.

    0 讨论(0)
  • 2020-12-14 00:53

    I achieved this using https://github.com/symfony/Intl:

    Symfony\Component\Intl\Intl::getCurrencyBundle()->getCurrencySymbol('EUR')
    

    returns

    '€'.
    
    0 讨论(0)
  • 2020-12-14 01:00

    If you set the locale using this function setlocale("LC_ALL", "es_AR"); You can use localeconv()['currency_symbol'] or localeconv()['int_curr_symbol'] to get the locale currency symbol and the international variation of the currency symbol.

    0 讨论(0)
  • 2020-12-14 01:02

    First of all, there is no international global currency symbol table, that anyone on the planet could read and understand.

    In each region/country the currency symbols will differ, that`s why you must determine them based on who is reading, using the browser / user locale.

    The correct way is as you guessed, using NumberFormatter::CURRENCY_SYMBOL, but you first have to set the appropriate locale like en-US@currency=JPY:

    $locale='en-US'; //browser or user locale
    $currency='JPY';
    $fmt = new NumberFormatter( $locale."@currency=$currency", NumberFormatter::CURRENCY );
    $symbol = $fmt->getSymbol(NumberFormatter::CURRENCY_SYMBOL);
    header("Content-Type: text/html; charset=UTF-8;");
    echo $symbol;
    

    This way the symbol will be understandable by the user.

    For example, $symbol will be:

    • Canadian dollar (CAD) : CA$ in USA, CAD in Romania , $CA in Iran
    • Iran Rial (IRR): IRR in USA, while in Iran will be
    0 讨论(0)
  • 2020-12-14 01:07
    Zend_Locale::getTranslationList('CurrencySymbol')
    

    Will give you an associative array of 3 letter currency codes to their symbol.

    Can then use like this:

    $curArr = Zend_Locale::getTranslationList('CurrencySymbol');
    echo $curArr['GBP'];
    
    0 讨论(0)
提交回复
热议问题