Gettext translations
Gettext is a great way to localize and internationalize (simply put, to translate) your (web)applications. It’s especially useful when you’re building a multi-language application because you can separate the code from the translation process effectively.
-
all strings that need to get translated have to be wrapped in _() function in the source code files:
echo _('text to be translated');
-
cd to the project directory and run in bash (this will go through all the php files in the current working directory):
xgettext --from-code=UTF-8 -d projectname *.php
-
to search for all php files in the project directory recursively, try this:
find . -iname "*.php" | xargs xgettext --from-code=UTF-8 -d projectname
If you need to omit a particular directory, use inverted grep like this:
find . -iname "*.php" | grep -v "/omitted_directory/" | xargs xgettext --from-code=UTF-8 -d projectname
-
To use this binary file, create another directory in your project folder (I’m using cz_CS locale identifier)
./translation/cs_CZ/LC_MESSAGES
and copy the .mo file there.
-
In your application, use the following:
$languange = 'cs_CZ'; putenv("LANG=$language"); setlocale(LC_ALL, $language); bindtextdomain("projectname", "./translation/"); textdomain("projectname"); bind_textdomain_codeset("projectname", 'UTF-8');
This will load the .mo file with translated strings and replace all the _() wrapped strings in there.