Search code examples
phpzend-framework2currency-formatting

From the locale, how do I get the currency code?


PHP has an intl module which allows for some cool things - like getting the currency symbol when using the NumberFormatter class. But this is making a massive assumption - that you already have the currency code of the currency you want to get the symbol for.

How do I get the currency code for any specific locale?

For example: en_gb => gbp, en_us => usd, es_es => eur

I am doing this so I can use the currencyFormat view helper in ZendFramework 2:

$locale = 'en_gb'; //from get parameter
$symbol = 'GBP'; //How do get this?

$this->serviceManager
         ->get('viewhelpermanager')
         ->get('currencyFormat')
         ->setLocale($locale)
         ->setCurrencyCode($symbol);

Solution

  • Based on the answer from Get currency ISO 4217 code based on locale (thanks @avy for link in comment),

    $locale = 'en_gb'; //from $_GET parameter
    
    //get symbol for this locale
    $symbol = \NumberFormatter::create(
        $locale,
        \NumberFormatter::CURRENCY
    )->getTextAttribute(\NumberFormatter::CURRENCY_CODE);
    
    //Add locale to currency formatter so we get correct symbol and formatting
    $this->serviceManager
            ->get('viewhelpermanager')
            ->get('currencyFormat')
            ->setLocale($locale)
            ->setCurrencyCode($symbol);