Gettext in PHP - minimal example

PHP Programming WIP

Contents

  1. About
    1. Requirements
  2. Preliminaries
    1. Create project directory
    2. Check that gettext is installed
  3. Create message catalog
    1. Select locale to use
    2. Create catalog (messages.po)
    3. Compile to binary format (messages.mo)
  4. Create PHP program

About

Minimal example of using gettext in PHP.

Requirements

Working webserver with PHP and gettext for PHP installed.

Preliminaries

Create project directory

Go to your webroot directory, and create new gettext-testing directory there. All files in this example will be placed under this directory.

Check that gettext is installed

Create file gettext-testing/phpinfo.php with following contents:

  <?php phpinfo(); ?>
Then open http://yourhost/gettext-testing/phpinfo.php in webbrowser and search for 'GetText' on that page. You should see 'GetText Support enabled' there.

Create message catalog

Select locale to use

In this example I will translate English to Italian, and I'll be using locale it_IT which means Italian of Italy. (TODO: explain more)

The locale you are using needs to be available for it to work. Run locale -a to see all available locales. If the locale you selected is not listed, you need to run sudo locale-gen LOCALE to generate it, i.e. sudo locale-gen it_IT for this example.

Create catalog (messages.po)

Gettext requires specific directory structure. Create directory gettext-testing/locale/it_IT/LC_MESSAGES and then create file messages.po there with following contents:

  msgid ""
  msgstr ""
  "Content-Type: text/plain; charset=UTF-8\n"

  msgid "Hello"
  msgstr "Ciao"

  msgid "Good morning"
  msgstr "Buongiorno"
The first part (lines 1-3) with empty msgid is special header. For now I'll just define Content-Type there.

After the header are the actual translations. msgid is the text to be translated and msgstr is the translated text.

Compile to binary format (messages.mo)

messages.po is human-readable and easy to edit message catalog. This needs to be compiled into binary-format file messages.mo before it can be used.

For now I'll use command-line program msgfmt to compile this. Open command prompt and go to LC_MESSAGES directory. Then use following command to compile the catalog:


  msgfmt messages.po --output-file messages.mo

Create PHP program

Create file gettext-testing/test.php with following contents:

  <?php
  $lang = 'it_IT';
  putenv('LC_ALL=' . $lang);
  setlocale(LC_ALL, $lang);

  $domain = 'messages';
  bindtextdomain($domain, 'locale');
  bind_textdomain_codeset($domain, 'UTF-8');
  textdomain($domain);

  echo gettext('Hello');
Then open http://yourhost/gettext-testing/test.php in webbrowser and you should see translated text 'Ciao' there.