Overview
Localizing/internationalizing any PHP application is easy through gettext functions. Basically you'll have a set of localization files (*.po
) that have a binary format version (*.mo
) across a simple and standard directory structure. Then gettext functions will use existing binary files based on current language locale.
Directory structure and localization files
locale/
├── en_US
│ └── LC_MESSAGES
│ ├── messages.mo
│ └── messages.po
└── pt_PT
└── LC_MESSAGES
├── messages.mo
└── messages.po
*.mo
files are to be auto generated based on pot (*.po
) files.
pot file example
In this case the file was generated using Poedit but you can create using your favorite editor.
msgid ""
msgstr ""
"Project-Id-Version: YouProjectID\n"
"POT-Creation-Date: 2013-07-30 12:44-0000\n"
"PO-Revision-Date: 2013-07-30 12:56-0000\n"
"Last-Translator: James Brown <jb@uuuuuuuuuuu.com>\n"
"Language-Team: jb@Music <jb@uuuuuuuuuuu.com>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 1.5.7\n"
"X-Poedit-KeywordsList: _;gettext;gettext_noop\n"
"X-Poedit-Basepath: .\n"
"X-Poedit-SourceCharset: UTF-8\n"
"Language: English\n"
msgid "TotalOnPayment"
msgstr "Total on payment"
This example contains one localized string identified by TotalOnPayment.
Create a bash script for generating locales binary (*.mo) files
gettext functions will read binary files that must be generated. This is a requirement and can be easily satisfied with the help of simple bash script:
#!/bin/sh
# repeat for all needed *.po files
find . -name \*.po -execdir msgfmt messages.po -o messages.mo \;
Make script file executable:
$ chmod +x generate-locales-binaries.sh
For example if saved as generate-locales-binaries.sh
every time you edit .po
files just execute to have all binaries updated:
$ ./generate-locales-binaries.sh
Set locale on your PHP code
<?php
// I18N support
$language = 'pt_PT';
putenv("LANG=$language");
setlocale(LC_ALL, $language);
// set the text domain as 'messages' and
// define where *gettext* is going to find your resources
$domain = 'messages';
bindtextdomain($domain, "locale");
textdomain($domain);
Usage example
<?php
/* ... */
echo(gettext('TotalOnPayment'));
/* ... */
The output would be...
Total on payment