Localize Your Web Application for Any Country With the Google Translate API

Final product image
What You'll Be Creating

In my tutorial Localization With I18n for the Building Your Startup With PHP series, I created sample Spanish code by cutting and pasting text strings into Google Translate. I began to wonder if I could integrate the Google Translate API with the Yii Framework's I18n resource extraction script to automate translation for a number of countries. I posted a feature request at the Yii Forum and then decided to see if I could build the feature myself.

In this tutorial, I'll walk you through my extensions to the Yii I18n extract script which do exactly this. And I'll demonstrate translating my startup application, Meeting Planner, into a handful of languages.

Keep in mind, Google Translate isn't perfect and it doesn't address issues related to time and date formats and currencies. But for a quick and affordable (free) way to build default translations for your web application into 50+ languages, this is an ideal solution.

For example, though, here's a more noticeable error I ran into in testing—luckily these are rare:

If you need a more professional approach, a friend pointed me to a paid service for managing localization within apps, Transifex. I haven't checked it out myself but it looks intriguing.

Working With Google Translate

What Languages Does It Support?

Google Translate offers translation services for 64 languages, including Swedish but sadly not Swedish Chef:

Here's a sampling of Google's supported languages—see the full list here:

Google Translate List of Languages Supported

Talking to the Google Translate API

I found two Composer libraries for working with the Google Translator API in PHP:

I found Velijanashvili's first so it's what I used in this tutorial. It leverages Google Translate through its free RESTful web interface so you do not need an API key. However, if you have a large library of resources or plan to translate many languages, you'll likely want to integrate Tillotson's as it is fully integrated with Google Translate's paid service via keys.

For this tutorial, I'm building on the Building Your Startup With PHP series codebase. To install Velijanashvili's Google Translate Library, just type:

Here's some sample code to translate from English to Spanish:

It should output:

hola mundo

Extending Yii2's I18n Message/Extract Script

How Yii2's I18n Support Works Today

At this time, you may want to review my Localization With I18n tutorial which explains how to extract message strings for your necessary language translations. 

You can use Yii's Gii code generator to generate models and CRUD code which automatically integrates I18n support. Every string in the code is replaced by a function call such as Yii::t('category','text string to translate');.

Yii offers a console command message/extract which finds all these function calls in your application and creates a directory tree of files by language and category for translations of all of these strings.

Here's an example string file for German:

Here's an example of the directory paths:

Yii I18n Directory Structure For Message Files

Extending Message/Extract for Google Translate

I chose the approach of creating a replacement script called message/google_extract which would call Google Translate whenever it needed to translate a string.

Preventing Broken Code From Translating Tokens

Because I18n integrates parameter tokens in curly braces for variable values, I ran into some problems right away. For example, here are some I18n strings which include tokens and nested tokens:

The Google Translate API does not have a parameter for ignoring tokens such as these in this form. But we can't translate these because they correspond to variable names and format strings in code.

It did not appear to me that a regular expression could solve this where translatable strings and tokens were present together. It's likely that readers may have a more efficient solution than I found for solving this problem—if one is clear to you, please post it in the comments.

I chose to scan the strings by character and track the nesting of curly braces. I'll be the first to admit there may be a better way. Here's my function parse_safe_translate():

It converts an I18n string into an array of elements separated into translatable and untranslatable elements. For example, this code:

Generates this output:

Whenever the extract process identifies a new string to translate, it breaks the string into these parts and calls the Google Translate API for any translatable string, e.g. one that doesn't begin with a left curly brace. Then it concatenates those translations with the tokenized strings back into a single string.

Translating a Tokenized String With Google Translate

Here's the function getGoogleTranslation() for a string and a destination language. The source language is determined by Yii::$app->language.

I found that the combination of these approaches worked almost perfectly in my testing.

Customizing Yii's Message/Extract

Yii's I18n implementation supports loading resource strings from .PO files, .PHP files (which I use) and the database. For this tutorial, I've customized Message/Extract for the PHP file generation.

I copied and extended message/extract in /console/controllers/TranslateController.php. Because of PHP 5.6.x's strict rules, I changed the function names for saveMessagesToPHP to saveMessagesToPHPEnhanced and saveMessagesCategoryToPHP to saveMessagesCategoryToPHPEnhanced.

Here's the saveMessagesToPHPEnhanced() function:

It calls the saveMessagesCategoryToPHP function:

Unfortunately, the original Message/Extract code is not commented. While there may be some additional improvements that can be made, I simply added a call to the Google Translate API here:

And I added a parameter ($force=true) to force recreation of the message files:

Translating Message Planner

Testing complete, I was excited to translate Message Planner into more languages. First, we add the new language translations to the /console/config/i18n.php file:

Again, if you need broader language support or have a larger quantity of strings to translate, you may want to switch to Travis Tillotson's Google Translation Client and paid API access.

Then, I added translation strings /frontend/views/layouts/main.php and /frontend/views/site/index.php in order to demonstrate translating the home page. Since these pages aren't generated by Yii's Gii code generator, the text strings had been left in plain HTML. Here's an example of what they look like now:

Here's what the home page looks like in English:

Meeting Planner English Home Page

Then, I ran google_extract:

Note: Be sure when you do this that the application language is set to your default language, e.g. English. This setting is in /common/config/main.php:

I found that it was necessary to run google_extract once to create the initial message file template and a second time to initiate the calls to Google Translate.

Then I can change the language setting in /common/config/main.php to see each translation. The results are pretty incredible for something that can be generated so quickly.

Here's the home page in Chinese:

Meeting Planner Chinese Home Page

Here's the home page in Arabic:

Meeting Planner Arabic Home Page

Here's the home page in Japanese:

Meeting Planner Japanese Home Page

Here's the home page in Yiddish:

Meeting Planner Yiddish Home Page

Here's the home page in German:

Meeting Planner German Home Page

What's Next?

I hope you enjoyed this tutorial. It was fun to write something that had such a broad impact on the potential reach of my Meeting Planner application. If you'd like to learn more about Meeting Planner, watch for upcoming tutorials in our Building Your Startup With PHP series. There are lots of fun features coming up.

Please feel free to add your questions and comments below; I generally participate in the discussions. You can also reach me on Twitter @reifman or email me directly.

Related Links

Tags:

Comments

Related Articles