Tuesday, July 30, 2013

PHP and JavaScript internationalization

These days I’ve been working on a PHP/JavaScript project which needed to be translated from English into other languages. I made a search and the results were pretty disappointing. All the solutions I’ve came across were either too complicated, too heavy or too messy. I wanted something more hygienic, that could be easily integrated into any project, so I ended up writing my own.

Basically, all you have to do is add a subdirectory called “i18n” (or any other name you want) and copy the “i18n.php” file there, then create a file to each language you need. One of those language files will be your default – probably the English one –, where the strings will also serve as the mapping keys. The other language files will simply have all the lines, one by one, translated.

Once the “i18n.php” file is included into your PHP script, you’ll have to set up the translation by calling i18n_set_map(), choosing the source (the default) language file, and the target language. And it’s done. Every string passed to the I() function will be translated, both in PHP and JavaScript.

There is a comprehensive example on the GitHub repository, where I published everything under the MIT license, in the hope that it can be useful to someone else. The repository is at github.com/rodrigocfd/php-js-i18n.

1 comment:

Greg David said...

Hi there! If you need to translate your PHP/Javascript project into multiple languages, you may consider using a l10n tool, and I would recommend using https://poeditor.com