Dynamically Translate Text using Google Translation API in PHP
Are you looking for a service that allows you to translate text into different languages? You are probably building a multi-language website where you need to write a translated copy for your content. Adding the translated text manually becomes difficult if the content is large. Also, you require a person who speaks another language. Overall, it’s a time-consuming process and you might require to spend a lot of money.
On the Internet, you will find a number of language translator tools. Google Translate is one of them. But, again you need to perform manual work on these tools. What if you want to build a program that automatically translates content into target languages?
The user can resolve this situation by using the Google Cloud Translation service. The Google Translation API is part of the larger Cloud Machine Learning API family. Through this API, you can translate text into all major languages. In addition to this, the service is affordable. Google charges a nominal fee for its usage. Check out their pricing for a better understanding.
Most of you probably heard when it comes to machine learning, Python is the best option. That’s true. But using the Google Cloud APIs, you can also integrate the power of machine learning in other programming languages to some extent. Google Cloud provides supported libraries in all major programming languages. All you need to do is call their APIs along with the data. In response, you will get the expected results.
For example, sentiment analysis comes under the machine learning category. And you can do sentiment analysis in PHP using Google Natural Language API.
On a similar note, in this article, we study how to dynamically translate text using Google Translation API in PHP. Under the hood, Google uses machine learning and gives a final translated text.
Getting Started
In order to use Google Cloud services, you need to authenticate your Google account. You are required to create a service account and download the JSON file containing your credentials. Follow the steps below which I have taken from Google Docs.
- In the Cloud Console, go to the Create service account page.
- Select a project.
- In the Service account name field, enter a name. The Cloud Console fills in the Service account ID field based on this name. In the Service account description field, enter a description.
- Click Create.
- Click the Select a role field. Under Quick access, click Basic, then click Owner.
- Click Continue.
- Click Done to finish creating the service account.
Create a service account key:
- In the Cloud Console, click the email address for the service account that you created.
- Click Keys.
- Click Add key, then click Create new key.
- Click Create. A JSON key file is downloaded to your computer.
- Click Close.
On the selected project, you must enable the Cloud Translation API via the API Library section. This service is part of the Google Cloud Platform so you need to enable billing on your account.
Copy the JSON file into your project directory. Keep this file in a safe place. You should also remove this file from the git commit using the .gitignore .
Translate Text using Google Translation API in PHP
Once you are ready with the JSON file of your service account, you can easily authenticate your account. First, install the cloud-translate package using the below command.
composer require google/cloud-translate
Upon installation, the following code will be used for the authentication.
'JSON_FILE_PATH' ]); > catch(Exception $e) < echo $e->getMessage(); >
You shouldn’t get any errors from the above code. It allows you to interact with Google Translation API through the $translate object.
While doing the translation, you have to use the ISO-639-1 code of a target language. For instance, let’s translate a text from English to French as follows. The ‘fr’ is an ISO-639-1 code for the French language.
'JSON_FILE_PATH' ]); $result = $translate->translate('Hello world!', [ 'target' => 'fr' // 'fr' is a ISO-639-1 code ]); echo $result['text']; > catch(Exception $e) < echo $e->getMessage(); >
The above code will give you a French translation of ‘Hello world!’ as ‘Bonjour le monde!’.
Using Google Translation API, you can also detect the language of a text. In response, you will get an ISO-639-1 code of the detected language. Let’s say I am passing a string in the French language.
$result = $translate->detectLanguage('Bonjour le monde!'); echo $result['languageCode']; // output is 'fr'
Discovering Supported Languages
If you want to see a list of all languages available for translation, use the code below.
$languages = $translate->languages(); foreach ($languages as $language)
You can also get a listing of supported languages for the target language as follows.
$languages = $translate->localizedLanguages([ 'target' => 'en' ]); foreach ($languages as $language)
I hope you understand how to dynamically translate text using Google Translation API in PHP. Please share your thoughts and suggestions in the comment section below.
Related Articles
If you liked this article, then please subscribe to our YouTube Channel for video tutorials.
1 thought on “ Dynamically Translate Text using Google Translation API in PHP ”
Hi,
there is the possibility to know the API usage quota to avoid exceeding the monthly limit.
You can enter an example, I think it would be very useful
Using Google Translate in PHP
After Hacking Google Voice API, We are about to hack Google Translate this time! We are going to write a full featured yet basic class in php to help us use Google Translate. The best part is that it is going to be lightweight and dependency-free.
Let’s start by defining properties for our GoogleTranslate class, let’s think of it this way: we need a variable to hold the original language, another one to hold the language which we are translating to, a result holder and an extra one to hold the api url format, used in the curl request later.
The $LangFrom and $LangTo variable need setters, this is how we are going to do it
public function setLangFrom($lang) < $this->langFrom = $lang; return $this; > public function setLangTo($lang) < $this->langTo = $lang; return $this; >
You may wonder why would I write return $this, which means that these two function will return a reference to the object after affecting the properties. This technique is called method chaining which enables us to make multiple calls for different methods in the same line. A good example would be helpful, let’s see the class constructor
public function __construct($from = "en", $to = "fr") < $this->setLangFrom($from)->setLangTo($to); >
This should be enough to setup parameters for the request. But we need a method that would actually trigger the connection. Things would be easier if we chose to use curl
public static final function makeCurl($url, array $params = array(), $cookieSet = false) < if (!$cookieSet) < $cookie = tempnam("/tmp", "CURLCOOKIE"); $curl = curl_init($url); curl_setopt($curl, CURLOPT_COOKIEJAR, $cookie); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_exec($curl); >$queryString = http_build_query($params); $curl = curl_init($url . "?" . $queryString); curl_setopt($curl, CURLOPT_COOKIEFILE, $cookie); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $output = curl_exec($curl); return $output; >
The process is divided in two steps: a first call is done to retrieve cookies information (if given), then a second call to request real data using the previous cookies. If you are too impatient, you have probably tried the script at this stage, if you did, you would notice that it works! it only needs some filtering that is what the next method does
public function translate($string) < $url = sprintf(self::$urlFormat, rawurlencode($string), $this->langFrom, $this->langTo); $result = preg_replace('!,+!', ',', self::makeCurl($url)); // remove repeated commas (causing JSON syntax error) $resultArray = json_decode($result, true); return $this->lastResult = $resultArray[0][0][0]; >
This method patches the placeholders in the $urlFormat, makes the request, cleans out the received data, decode it and extracts the main result from it. This is quite simple to figure out on your own, you just need to play with the real Google Translate page to know what to do. Now the class is ready and fully functional. Go ahead and create a new file in the same directory as the first one, write the following
isn’t this great! This was pretty easy and short. Go ahead and take a look at my gist, you will get the complete class assembled, with an extra method that i have included which can be called statically, having all the data as parameters, I will let you discover it on your own. If you find this tutorial useful, follow me here and on social networks to get updated for new tutorials.