jump to content
Snippets and tips
  1. Home
  2. Holiday
  3. Posts
  4. Tools
  5. Tags
  6. Categories

Gettext for PHP


Gettext is an extension for PHP like for many other languages that supports internationalization.

The documentation of gettext in PHP is scattered and it takes some experimenting to get it to work.

Preparations #

The system depends on installed locale on the host system. The command locale -a give an account which locale have been installed. Background might be that setting locale in a program also requires more support for formatting from the system then what is obvious.

On my system, the following locale are available:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
C
C.utf8
de_DE
de_DE.iso88591
en_US
en_US.iso88591
en_US.utf8
nb_NO
nb_NO.iso88591
nb_NO.utf8
POSIX
pt_PT
pt_PT.iso88591
pt_PT.utf8
ru_RU.utf8

If one needs additional languages, one needs to add that language to /etc/locale.gen and run locale-gen.

Application domain #

Lets say, the application is name myapp, this needs to be implemented several places in php.

1
2
3
error_log(bindtextdomain('myapp', __DIR__ . '/locale/'));
error_log('new domain is ' . textdomain('myapp'));
error_log('new locale is ' . setlocale(LC_MESSAGES,'nb_NO.utf8'));

This requires the presence of a compiled message file myapp.mo in the following location locale/nb_NO.utf8/LC_MESSAGE.

Compiling a message file #

To get there, one needs to process the php files first. This is done by:

1
xgettext input.php

This produces a file message.po, that has the following content:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2024-03-04 21:18+0100\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: nb_NO.utf8\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"

#: public/index.php:8
msgid "hello world"
msgstr "hei verden"

Line 8 must contain the correct locale-id, in this case it is nb_NO.utf8 as it was found by locale -a. Line 11 must be changed to character set UTF-8.

This is then compiled by

1
msgfmt -o locale/nb_NO.utf8/LC_MESSAGES/mychat.mo messages.po 

Since the translation was made to Norwegian, the resulting compiled file must be stored in that location.

Caching by the PHP engine #

NOTE: the compiled message files are only loaded once. One needs to restart php, php-fpm or mod_php for it to reload the compiled message files with changed content.

1
<?= _('hello world')?>

will then return “hei verden”.

Further reading #

Of course, the internet has more resources: GNU .