Using gettext in PHP

Our sample application is the following:

We would like to have the "window title", "Translation test" and "Close window".

The first thing you need to do is loading the gettext extension, the same way you load php-gtk. This can be done by doing a
if( !extension_loaded( 'gettext')) {
    if( !@dl( 'php_gettext.' . PHP_SHLIB_SUFFIX)) {
        die( 'gettext is not available');

The next step is to set the location of the translation file; this can be done with
bindtextdomain( 'testapp', './locale'); 
which would assume that the .mo file would be in {CURRENT_DIR}/locale/{LANGUAGE}/LC_MESSAGES/ Language could be de_DE, depending on your system setting - this can be overridden with
putenv( "LANG=" . 'de_DE'); //required on windows, because setlocale doesn't really work
setlocale( LC_ALL, 'de_DE');
. You should always use the language identifier together with the country code as there have been problems on some systems when using only de or DE. The {CURRENT_DIR} assumes that the application is started with the working directory in the application directory; but this can't always be expected. It would be better to do a
bindtextdomain( 'testapp', dirname( __FILE __) . '/locale'); 
which uses the real location of the current file as base.

After setting the file location, you have to tell gettext which "domain" (part of the translation files) you want to use, in our case it would be "testapp":
textdomain( 'testapp'); 
This allows you to use multiple domains in the same program, and you can switch between them everytime.

The translation of strings if an ease: There is the function gettext which takes a string as parameter and returns the translated version. To make the code more readable, there is an alias of the function: _ (underscore). Now we change our code and get the following:

When you start your application, you will see nothing translated: We forgot the translation file. Just copy the following into locale/de/LC_MESSAGES/testapp.po:
# PHP-Gtk translation tutorial
# Copyright (C) 2004 PHP-Gtk documentation team
# Christian Weiske <>, 2004.
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: 0.1N\n"
"POT-Creation-Date: 2004-09-15 07:12+0100\n"
"PO-Revision-Date: 2004-09-15 07:12+0100\n"
"Last-Translator: Christian Weiske <>\n"
"Language-Team: PHP-Gtk doc team germany <>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=iso-8859-1\n"
"Content-Transfer-Encoding: 8bit\n"
#: gettext_example.php:20
msgid "window title"
msgstr "Fenstertitel"

msgid "Translation test"
msgstr "UEbersetzungstest"

msgid "Close window"
msgstr "Fenster schliessen"
After doing this, compile it with msgfmt testapp.po and move the created to Start the application again - you will see the app in the german language.

© Copyright 2003-2014 The ultimate PHP Editor and PHP IDE site.