on Articles

Translate and Localize your web application with PHP and gettext

6 comments
php
Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInShare on RedditShare on StumbleUpon

Wikipedia says: Localization is the process of translating a product into different languages or adapting a language for a specific country or region.

There are several techniques that developer can use to localize an application. The most common ones are using arrays and gettext. I will try to explain both and how to use them.

Arrays

This is an easier method to implement but has some downsides. Basically, you create a separate file with language array for every language that you plan to implement. This file looks something like this:

$lang = array(
                        'title' => 'Some title',
                        'intro' => 'Enter intro text'
                );

This is an example file for English language. You simply save this file as en.php and create de.php file with German translations using the same variable:

$lang = array(
                        'title' => 'Einige Titel',
                        'intro' => 'Geben Sie Introtext'
                );

We have our language files ready, now create your index.php file and enter something like this:

<?php include('en.php'); ?> 
<h2><?php echo $lang['title']; ?></h2>
        
<p><?php echo $lang['intro']; ?></p>

So we include our english file and echoing some array values. If you run this file in browser, you should see text in English. Now change the first line to:

<?php include('de.php'); ?> 

Refresh the page and you will see that now you have German translation. Now, we need to do this in a better way. Simply add some links with get variables and according to them, include the proper language file. You store that value in $_SESSION for future use:

session_start();
if(isset($_GET['lang'])) {
    $_SESSION['lang'] = $_GET['lang'];
} 
if(!isset($_SESSION['lang'])) {
    $_SESSION['lang'] = 'en'; // default value
}
include($_SESSION['lang'] . 'php'); // include lang file

That’s it. Major downside is when the application is updated and additional strings are added, there is no way to determine which new strings were added and if they are present in every language.

Gettext

Using gettext to get translated strings couldn’t be easier. Just call gettext(“Title”) and you get a localized version of “Text to be translated” if available, or “Title” otherwise. If you’re lazy, you can use _() instead of gettext().

As you can see, there is need for just one translation file, as non-existing translations are rendered automatically.

So, enter this code in new index.php file:

<h2><?php echo _('Title'); ?></h2>

<p><?php echo _('Enter your intro text here'); ?></p>

Try to run this in your browser and you will see normal english strings.

Now, go to PoEdit website and download PoEdit program and install it. Launch PoEdit.

Create a new catalog (File -> new catalog). Choose the language you want to translate the application to. We are going to use German, GERMANY and utf-8 for both character sets. Leave the plural forms blank.

On the paths tab, set the base path to the directory containing your index.php file, and add “.” as a path. Click OK and save a file in folder /locale/de_DE/LC_MESSAGES/ which you must create as messages.po.

PoEdit will now automatically scan all source files inside the path you specified earlier and extract all strings that are passed to gettext() or _(). Click OK.

Now translate our two strings by clicking on them one by one and entering its german translation in lower box. Click Save. This will create messages.mo which will be used by PHP later.

Now add this to your index.php:

$lang = "de_DE";
if (isset($_GET['lang'])) $lang = $_GET['lang'];
putenv("LC_ALL=$lang");
setlocale(LC_ALL, $lang);
bindtextdomain("messages", "locale");
bind_textdomain_codeset('messages', 'UTF-8');
textdomain("messages");

If everything works fine (you should have gettext extension active in your PHP configuration), after refresh you should see German translation of our texts.

As you can see, gettext method allows you to see and edit languages far more intuitive and easier. Some say that arrays are faster, but Apache server is caching gettext string, so I think that the users of your application would not notice the difference in speed.

There are other methods available for localization in PHP, but those mentioned above are the most common.

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInShare on RedditShare on StumbleUpon



  • Pingback: Tweets that mention Translate and Localize your web application with PHP and gettext | CodeForest -- Topsy.com

  • Mastodont

    Gettext is simple but has two issues:
    - gettext extension must be installed
    - all used locales must be installed in the hosting system

  • Mike

    Great post, I have struggled on how to use gettext for a while. Your instructioins are pretty easy and functional :) Thank you

  • http://www.thomasvanhoutte.be Thomas Vanhoutte

    Thanks, I can certainly use getText on my own site (need to translate from English to Dutch).

  • Selçuk Terzi

    include($_SESSION['lang'] . ‘php’); => dot is missing before php
    include($_SESSION['lang'] . ‘.php’); –>correct

  • mobidyc

    Thank you for this gettext tutorial. It’s so easy with this ;)