Gettext translations

120px-Official_gnu.svgGettext 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.

  1. all strings that need to get translated have to be wrapped in _() function in the source code files:

    echo _('text to be translated');
  2. 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
  3. 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
  4. The above mentioned commands will output a file named projectname.po, which can be translated using Poedit or Pootle. Poedit will generate binary file on save.
  5. To use this binary file, create another directory in your project folder (I’m using cz_CS locale identifier)


    and copy the .mo file there.

  6. In your application, use the following:

    $languange = 'cs_CZ';
    setlocale(LC_ALL, $language); 
    bindtextdomain("projectname", "./translation/"); 
    bind_textdomain_codeset("projectname", 'UTF-8');

This will load the .mo file with translated strings and replace all the _() wrapped strings in there.