views:

319

answers:

1

I've always heard about gettext - I know it's some sort of unix command to lookup a translation based on the string argument provided, and then produces a .pot file but can someone explain to me in layman's terms how this is taken care of in a web framework?

I might get around to looking at how some established framework has done it, but a layman's explanation would help because it just might help clear the picture a bit more before I actually delve into things to provide my own solution.

+7  A: 

The gettext system echoes strings from a set of binary files that are created from source text files containing the translations in different languages for the same sentence.

The lookup key is the sentence in a "base" language.

in your source code you will have something like

echo _("Hello, world!");

for each language you will have a corresponding text file with the key and the translated version (note the %s that can be used with printf functions)

french
msgid "Hello, world!"
msgstr "Salut, monde!"
msgid "My name is %s"
msgstr "Mon nom est %s"

italian
msgid "Hello, world!"
msgstr "Ciao, mondo!"
msgid "My name is %s"
msgstr "Il mio nome è %s"

These are the main steps you need to go through for creating your localizations

  • all your text output must use gettext functions (gettext(), ngettext(), _())
  • use xgettext (*nix) to parse your php files and create the base .po text file
  • use poedit to add translation texts to the .po files
  • use msgfmt (*nix) to create the binary .mo file from the .po file
  • put the .mo files in a directory structure like

locale/de_DE/LC_MESSAGES/myPHPApp.mo

locale/en_EN/LC_MESSAGES/myPHPApp.mo

locale/it_IT/LC_MESSAGES/myPHPApp.mo

then you php script must set the locale that need to be used

The example from the php manual is very clear for that part

<?php
// Set language to German
setlocale(LC_ALL, 'de_DE');

// Specify location of translation tables
bindtextdomain("myPHPApp", "./locale");

// Choose domain
textdomain("myPHPApp");

// Translation is looking for in ./locale/de_DE/LC_MESSAGES/myPHPApp.mo now

// Print a test message
echo gettext("Welcome to My PHP Application");

// Or use the alias _() for gettext()
echo _("Have a nice day");
?>

Always from the php manual look here for a good tutorial

Anonymous