Localizing PHP Applications “The Right Way”, Part 1

Share this article

New audiences around the world access the Internet every second, most of whom would be delighted to find your content in their mother tongue. You might think you only need a good translator to translate the user interface of your website, an easy task nowadays given how easy it is to find one, but the bigger challenge isn’t translating or writing multilingual content… it’s writing the code behind the scenes. Localizing software applications in general used to be a cumbersome and error-prone task resulting in a lot of messy code. Some developers even use different versions of code for the same application but for different locales, which makes managing the codebase practically impossible. Enter gettext, the wonderful open-source tool that will make your life easier by allowing you to concentrate on your code. Localization becomes a matter of writing separate translation files for the target language, which can easily be done by a translator using Poedit. If you master gettext for PHP, you will find extending your application’s global reach really can be just a matter of translation! In this series of articles you will learn how to gettext to localize your PHP application. Part 1 will provide just a quick foray into gettext. Each subsequent part will build on preceding parts, teaching you how to handle multiple translation domains, plural forms, and even how you can automate some of the localization process.

Preparing the Environment

I prefer to make sure my environment is set up properly before I start learning something new, since having everything up and running correctly makes it easier to test what I learn step-by-step. Here is a checklist of things you need to have installed before going any further:
  • PHP 5.x on Apache (or whichever web server you prefer), with the gettext extension enabled. You can always get the latest PHP for your platform at www.php.net.
  • Poedit, a cross-platform editor for gettext catalogs. It’s a really nice tool that lets you keep your translations separate from your application code. You can get a copy from www.poedit.net
Regardless of your platform, to use gettext from PHP you will need to have the gettext library installed and the PHP extension that hooks into the library. Ubuntu/Debian users can use apt-get and Fedora/CentOS/Redhat users can use yum to install the gettext library. If you’re using another unix-like system, go to www.gnu.org/s/gettext and get a copy of gettext that is compatible with your platform. Windows users can download the latest executable and install it from gnuwin32.sourceforge.net/packages/gettext.htm. After you install the library, you need to enable the PHP extension for gettext by editing php.ini and adding a single line:
# for Windows users
extension=php_gettext.dll
# for *nix users
extension=gettext.so
Then, install Poedit which will be used later. You can download a copy from www.poedit.net.

Hello World with gettext

In your web root directory, create a sandbox directory for playing with gettext named TestI18N (I18N stands for Internationalization). Within the TestI18N directory, create the following hierarchy:

directory structure

In future projects, you can really name the parent directory and the Locale
directory any name you want, but en_US and LC_MESSAGES are standard names which are used by gettext. en_US stands for the name of the locale and is made up of two parts. The first part is a two-letter lowercase abbreviation for the language according to the ISO 639-1 specification. The second part after the underscore is a two-letter uppercase country code according to the ISO 3166-1 alpha-2 specification. en_US thus means the language is English as spoken in the United States. Next, make sure Poedit is working correctly on your platform. Launch the program and choose from the top menu bar File > New Catalog. In the settings window, fill in the information below skipping the plural forms field for now:

poedit settings window

Click OK and then save the file as messages.po inside the LC_MESSAGES directory you created earlier. Now close Poedit, and use your favorite text editor to open messages.po… yes, it is an ordinary text file! you can edit it by hand, but to save ourselves some hassle we let Poedit create the main definitions for us. Leave an empty line after the lines that are already in the file and add the following:
#Test token 1
msgid "HELLO_WORLD"
msgstr "Hello World!"

#Test token 2
msgid "TEST_TRANSLATION"
msgstr "Testing translation..."
Save messages.po and close it, and then re-open it in Poedit. In Poedit, choose File
> Save or click the Save Catalog entry in the icon bar. The reason we are saving the PO file in Poedit is because they need to be compiled into a special format usable by gettext. After you save it in Poedit, you will see a new file has been created in the same directory with the same name but with the extension .mo. If you were to continue to modify and save the PO file with a regular text editor, you would need to compile it using the pocompile command. The extra compilation step isn’t necessary if you use Poedit because it automatically compiles the file anytime you save it. Back in the TestI18N directory, create a file named test-locale.php with the following code:
<?php
// I18N support information here
$language = "en_US";
putenv("LANG=" . $language); 
setlocale(LC_ALL, $language);

// Set the text domain as "messages"
$domain = "messages";
bindtextdomain($domain, "Locale"); 
bind_textdomain_codeset($domain, 'UTF-8');

textdomain($domain);

echo _("HELLO_WORLD");
Open TestI18N/test-locale.php in your browser. If everything is installed correctly and working fine, you will see Hello World displayed on the page.

Summary

When it comes to localizing your PHP application, you may have a lot of options at your disposal. We chose to use the GNU gettext library and its PHP extension, a powerful and easy approach that localizes the application “The right way!” In this installment you saw what’s needed to install gettext and the PHP extension, briefly used Poedit, and whetted your appetite with a simple Hello World script. Part 2 will use this as a basis for learning more about gettext; I’ll explain each function introduced in the Hello World script as well as how the gettext library works. Image via sgame / Shutterstock

Frequently Asked Questions on Localizing PHP Applications

What is the importance of localizing PHP applications?

Localizing PHP applications is crucial for businesses that aim to reach a global audience. It involves translating the user interface and other visible elements of a software application into different languages. This process not only enhances the user experience but also increases the market reach of the application. By localizing your PHP application, you can cater to a diverse audience, thereby increasing your user base and potential revenue.

How does PHP localization work?

PHP localization involves using specific functions and libraries to translate the text within your application. The most common method is using gettext, a powerful library that allows you to wrap your strings in a function that will translate them based on the user’s locale. This involves creating a .po file for each language, which contains all the translations.

What are the steps to implement PHP localization?

Implementing PHP localization involves several steps. First, you need to install and configure the gettext library in your PHP environment. Next, you need to wrap all the strings in your application that you want to translate using the gettext function. Then, you need to create .po files for each language you want to support, and translate all the strings in these files. Finally, you need to compile these .po files into .mo files, which are binary and can be read by gettext.

What are the challenges in localizing PHP applications?

Localizing PHP applications can be challenging due to several reasons. First, it can be time-consuming to translate all the strings in your application, especially if it is large and complex. Second, maintaining the translations can be difficult, especially when you update or add new features to your application. Third, it can be tricky to handle plurals, gender, and other grammatical nuances in different languages.

How can I handle plurals in PHP localization?

Handling plurals in PHP localization can be done using the ngettext function. This function takes three arguments: the singular form of the string, the plural form, and the number. It then returns the correct form based on the number. For example, ngettext(“one apple”, “many apples”, $number) would return “one apple” if $number is 1, and “many apples” otherwise.

How can I test my localized PHP application?

You can test your localized PHP application by changing the locale on your server or in your PHP code, and then checking if the strings are correctly translated. You should also test the layout and design of your application in different languages, as some languages may require more space or have different reading directions.

Can I use machine translation for PHP localization?

While machine translation can be a quick and easy way to translate your strings, it is not recommended for PHP localization. Machine translation often lacks the accuracy and context-awareness needed for software localization. It is better to use professional translators or localization services to ensure the quality of your translations.

How can I manage the translations for my PHP application?

Managing the translations for your PHP application can be done using a localization platform or a translation management system. These tools allow you to store, manage, and update your translations in a centralized place. They also provide features like translation memory, glossaries, and collaboration tools to help you streamline your localization process.

What is the role of .po and .mo files in PHP localization?

.po and .mo files play a crucial role in PHP localization. .po files are text files that contain the original strings and their translations. They are human-readable and can be edited using a text editor or a .po file editor. .mo files, on the other hand, are binary files that are machine-readable. They are generated from .po files and are used by gettext to translate the strings in your application.

Can I localize my PHP application into any language?

Yes, you can localize your PHP application into any language that is supported by gettext. However, you need to have the translations for all the strings in your application in that language. Also, you need to consider the cultural and linguistic nuances of each language to ensure the quality of your localization.

Abdullah AbouzekryAbdullah Abouzekry
View Author

Abdullah Abouzekry is an experienced web-developer with over 7 years developing PHP/MySQL applications ranging from simple web sites to extensive web-based business applications. Although his main experience is with PHP/MySQL and related web technologies, he has developed and localized many desktop applications in C#, Python/Qt, Java, and C++. When not writing code, Abdullah likes to read, listen to oriental music, and have fun with his little family.

Intermediate
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form