Let's start with simple piece of code to format money with NumberFormatter
:
$formatter = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
echo $formatter->formatCurrency(123456789, 'JPY');
This prints: ¥123,456,789
.
This is ok if you want to format money.
But what I want to do is to get currency symbol (e.g. ¥) for given currency ISO 4217 code (e.g. JPY).
My first guess was to try using:
$formatter->getSymbol(NumberFormatter::CURRENCY_SYMBOL);
But that gives currency symbol for locale given in constructor (en_US), $ in my case.
Is there a way to get currency symbol by currency ISO 4217 code in PHP?
Since the symbols can be multi-byte I used mb_*() functions to correctly grab the all non-punctuation and non-digit chars which would just leaves the symbol.
Cryptic has a good answer, but there is a simpler way to do it:
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.
Will give you an associative array of 3 letter currency codes to their symbol.
Can then use like this:
I achieved this using https://github.com/symfony/Intl:
returns
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:
This way the symbol will be understandable by the user.
For example, $symbol will be:
If you set the locale using this function
setlocale("LC_ALL", "es_AR");
You can uselocaleconv()['currency_symbol']
orlocaleconv()['int_curr_symbol']
to get the locale currency symbol and the international variation of the currency symbol.