* The cover image is originally by anncapictures and edited with great appreciation.
Summary
PHP provides a very useful extension for multi-language support named intl. It means "internationalization".
This post shows how to install it (on OpenBSD) and use it with holding up Locale class as an example.
Environment
- OS: OpenBSD 6.9
- Programming Language: PHP 7.4
Description
Installation
First, get the extension as a ports package:
$ doas pkg_add php-intl quirks-3.632 signed on 2021-05-18T20:40:55Z Ambiguous: choose package for php-intl 0: <None> 1: php-intl-7.3.28 2: php-intl-7.4.19 3: php-intl-8.0.6 Your choice: 2 php-intl-7.4.19:icu4c-wwwdata-68.2v0: ok php-intl-7.4.19:icu4c-68.2v0: ok php-intl-7.4.19: ok
Then, activate it:
$ cd /etc/php-7.4 $ # enable extension $ doas ln -s ../php-7.4.sample/intl.ini $ # validate the symbolic link created $ ls -l total 0 ... lrwxr-xr-x 1 root wheel 26 May 20 11:05 intl.ini@ -> ../php-7.4.sample/intl.ini ... $ # load it $ doas rcctl restart php74_fpm
That's it.
Get localized display name with Locale::getDisplayLanguage
The intl extension is active now.
Let's use getDisplayLanguage function of Locale class in it. It brings "an appropriately localized display name for language of the inputlocale".
Example 1: Language names in current language
locale_get_display_language
, the "procedural style", is available instead of Locale::getDisplayLanguage
.
Almost all what to do is to pass locale string, which you want to convert to the display name, as the first parameter.
# prerequisites: # the default locale is en-US $arr = ['en', 'ja', 'de', 'es', 'fr', 'sv', 'ar']; # for example
If the second parameter is omitted, string shown in the default language is returned. For example, locale_get_display_language('ja');
this time means "Japanese in English".
foreach ($arr as $lang) { echo locale_get_display_language($lang); // or: echo Locale::getDisplayLanguage($lang); } # ==> # English # Japanese # German # Spanish # French # Swedish # Arabic
Example 2: Language names in each language
If the second parameter is passed to locale_get_display_language
or Locale::getDisplayLanguage
, string shown in the language is returned. For example, ocale_get_display_language('ja', 'ja');
means "Japanese in Japanese".
foreach ($arr as $lang) { echo locale_get_display_language($lang, $lang); // or: echo Locale::getDisplayLanguage($lang, $lang); } # ==> # English # 日本語 # Deutsch # español # français # svenska # العربية
S' wonderful🙂
Top comments (0)