Internationalization in PHP

Introduction

Internationalization (i18n) refers to the process of designing and developing a software application so that it can be easily adapted to various languages and regions without requiring changes to the code. This involves separating the language-specific content from the source code and providing translations for different languages.

Basics of Internationalization

What is Internationalization (i18n)?

Internationalization, often abbreviated as i18n (where 18 stands for the number of letters between 'i' and 'n'), involves making your application adaptable to different languages and regions. This includes translating text, formatting dates and numbers according to local customs, and supporting various currencies.

Why is i18n Important?

  • Reach a Global Audience: By supporting multiple languages, you can reach a wider audience.

  • User Experience: Users prefer to interact with applications in their native language.

  • Compliance: Some regions require applications to be available in the local language.

  • Business Growth: Expanding to new markets can drive business growth.

PHP Internationalization Functions

PHP provides several functions and extensions for internationalization. The most commonly used one is gettext.

gettext

The gettext function is used to retrieve translated strings. Here’s a simple example:

<?php
// Set the text domain as 'messages'
textdomain('messages');

// Translate the string 'Hello, World!'
echo gettext('Hello, World!');
?>

bindtextdomain

The bindtextdomain function sets the directory where the translation files are stored.

<?php
// Set the directory for the 'messages' domain
bindtextdomain('messages', '/path/to/locale');
?>

textdomain

The textdomain function sets the text domain to be used.

<?php
// Set the text domain as 'messages'
textdomain('messages');
?>

setlocale

The setlocale function sets the locale information.

<?php
// Set the locale to German
setlocale(LC_ALL, 'de_DE');
?>

Setting Up the Environment

Installing gettext

To use gettext in PHP, you need to have the gettext extension installed.

For Ubuntu/Debian:

sudo apt-get install gettext
sudo apt-get install php-gettext

For CentOS/RHEL:

sudo yum install gettext
sudo yum install php-gettext

Configuring PHP for gettext

Ensure that the gettext extension is enabled in your php.ini file.

; Uncomment the following line
extension=gettext

Restart your web server to apply the changes.

Creating Translation Files

Understanding .po and .mo Files

Translation files in gettext are stored in two formats:

  • .po files: Portable Object files are human-readable and editable.

  • .mo files: Machine Object files are binary and used by the gettext function for translations.

Tools for Creating Translation Files

There are various tools available for creating and managing translation files, such as Poedit and GNU gettext utilities.

Using Poedit:

  1. Create a new catalog.

  2. Define your project’s source code and translation languages.

  3. Extract strings and provide translations.

  4. Save the file, which will generate both .po and .mo files.

Implementing Internationalisation in PHP

Loading Translation Files

First, create a directory structure for your translations:

locale/
  en_US/
    LC_MESSAGES/
      messages.po
      messages.mo
  de_DE/
    LC_MESSAGES/
      messages.po
      messages.mo

Using gettext Functions in Your Code

Here’s an example of using gettext in a PHP script:

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

// Set the directory for the translation files
bindtextdomain('messages', './locale');

// Specify the text domain
textdomain('messages');

// Translate and print the string
echo gettext('Hello, World!');
?>

Handling Plural Forms

Different languages have different rules for pluralization. gettext provides support for this through the ngettext function.

<?php
// Example of using ngettext for plural forms
$count = 5;
echo ngettext('%d apple', '%d apples', $count);
?>

In the .po file, you would define plural forms like this:

msgid "%d apple"
msgid_plural "%d apples"
msgstr[0] "%d Apfel"
msgstr[1] "%d Äpfel"

Right-to-Left (RTL) Language Support

Supporting RTL languages like Arabic or Hebrew requires additional considerations, such as adjusting the layout and ensuring proper text alignment.

Example:

<?php
// Set the locale to Arabic
setlocale(LC_ALL, 'ar_SA');

// Set the directory for the translation files
bindtextdomain('messages', './locale');

// Specify the text domain
textdomain('messages');

// Translate and print the string
echo gettext('Hello, World!');
?>

Mini Project: Internationalised To-Do List Application

Project Setup

  1. Create the Directory Structure:

     to-do-app/
       index.php
       locale/
         en_US/
           LC_MESSAGES/
             messages.po
             messages.mo
         de_DE/
           LC_MESSAGES/
             messages.po
             messages.mo
    
  2. Create Translation Files:

  • Use Poedit or another tool to create translations for messages.po and generate messages.mo files.
  1. index.php:

     <?php
     // Set the locale based on user preference or default to English
     $locale = isset($_GET['lang']) ? $_GET['lang'] : 'en_US';
     setlocale(LC_ALL, $locale);
    
     // Set the directory for the translation files
     bindtextdomain('messages', './locale');
    
     // Specify the text domain
     textdomain('messages');
     ?>
     <!DOCTYPE html>
     <html lang="en">
     <head>
         <meta charset="UTF-8">
         <title><?php echo gettext('To-Do List'); ?></title>
     </head>
     <body>
         <h1><?php echo gettext('To-Do List'); ?></h1>
         <form>
             <input type="text" name="task" placeholder="<?php echo gettext('Enter your task'); ?>">
             <button type="submit"><?php echo gettext('Add'); ?></button>
         </form>
         <ul>
             <!-- Example of adding tasks -->
             <li><?php echo gettext('Sample Task 1'); ?></li>
         </ul>
     </body>
     </html>
    
  2. Run the Project: Open your browser and navigate to the project directory. Switch languages by appending ?lang=de_DE to the URL.

Conclusion

Internationalization in PHP is a powerful way to make your applications accessible to a global audience. By using gettext and following best practices, you can provide seamless multi-language support. This guide has covered the essentials, from setting up your environment to implementing i18n in your projects. With the provided mini-project, you now have a practical example to kickstart your internationalization journey.