Jan 06

Setup locale translation in PHP using gettext function

Translation in any website can be reached in several ways, but our favorite is using gettext functions provided natively into PHP. If you use some popular CMS like WordPress and you have translated CMS interface, surely you have came in touch with .po and .mo files . These ones are classic gettext file. You could find more informations about original project at official site .
For the moment, we want to show you how to use it in PHP to add locale functions in your project. Start writing a little of code:

$locale = "it_IT";
// We can set variable by GET in URL. It should be a valid code 
    $locale = $_GET["locale"];
//Set the environment variable, you could not need it but it's useful
//Now set locale information. LC_ALL represents all category functions
setlocale(LC_ALL, $locale);
// Set the directory of translation tables
bindtextdomain("myfile", "/locale");
// Set the domain
/* you should have this directory structure
* /locale
*       /it_IT
*             /LC_MESSAGES
*                         /myfile.omo

Really simple, to test it

// Use standard function
echo gettext("ThewordItranslated");
// Or use gettext alias _()
echo _("ThewordItranslated");

It doesn’t work? Some solutions:

  • Gettext library is not installed in you server. To check it, put some if statements in the above functions ( Ex if(setlocale….. ))
  • You miss directory structure

What if i want use .mo and .po files?But in my phpmyadmin installation and in other CMS how is it possible to use gettext?
Answere is : all are using opther library manipulating .po and .mo files. One such library phpmyadmin uses is here.

1 ping

  1. Using .mo and .po file without native gettext php function

    […] « Setup locale translation in PHP using gettext function […]

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>