Dynamically Translate Text using Google Translation API in PHP

Do you want to integrate 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 each text. 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 have to spend a lot of money.

You will find a number of language translator tools on the internet. 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 translates strings 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, we 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 we 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 technique. 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 techniques 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.

Create a service account:

  • 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. As this service is part of the Google Cloud Platform, 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 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, we 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.

<?php
require_once "vendor/autoload.php";

use Google\Cloud\Translate\V2\TranslateClient;

try {
    $translate = new TranslateClient([
        'keyFilePath' => '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.

<?php
require_once "vendor/autoload.php";

use Google\Cloud\Translate\V2\TranslateClient;

try {
    $translate = new TranslateClient([
        'keyFilePath' => '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 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) {
    echo $language . "\n";
}

You can also get a listing of supported languages in target language as follows.

$languages = $translate->localizedLanguages([
    'target' => 'en'
]);

foreach ($languages as $language) {
    echo $language['name'] . "\n";
    echo $language['code'] . "\n";
}

I hope you may learn 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.

Leave a Reply

Your email address will not be published. Required fields are marked *