Published on

PHP text auto translate using google translation API

Authors

For more information you can go to the documentation of Google translation API. But we will use the PHP SDK/Package. There are two packages using which you can implement translation functionality

  1. google/apiclient
  2. google/cloud-translate

I'll use google/apiclient. you can install via below command

$ composer require google/apiclient:"^2.0"

I'll assume you have enabled the translation feature in your google console. We are going to use oAuth to authenticate the application. You can check the documentation here.

use Google_Client;
use Google_Service_Translate;
use Google_Service_Translate_TranslateTextRequest;

class Translate {
    
    public static function(array $stringArray, string $sourceLang = 'en', string $targetLang = 'fr') {
        
        $client = new Google_Client();
        $client->useApplicationDefaultCredentials();
        $client->addScope(Google_Service_Translate::CLOUD_TRANSLATION);
        $service = new Google_Service_Translate($client);
        $projects = $service->projects;

        $postbody = new Google_Service_Translate_TranslateTextRequest();
        $postbody->setContents( array_values($stringArray) );
        $postbody->setSourceLanguageCode( $sourceLang );
        $postbody->setTargetLanguageCode( $targetLang );

        // extract translation from it
        $translatedTexts = $projects->translateText('projects/vaveio', $postbody)->translations;

        return $translatedTexts;
    }
}

As you can see I have initiated Google_Client. and authenticated request via OAuth. Which documentation you can check on GitHub repo of google/apiclient. then I have added the scope of the request. Google_Service_Translate class defines two scope CLOUD_PLATFORM which use to View and manage your data across Google Cloud Platform services. The other one is CLOUD_TRANSLATION, suing which we Translate text from one language to another.

Google_Service_Translate begin translation service. for the translation we need to provide a project name. like i have added projects/vaveio.

translateText( string projectName, Google_Service_Translate_TranslateTextRequest $postBody) second parameter is an object of Google_Service_Translate_TranslateTextRequest.

Translate::translate(['I am good man'], 'en', 'fr');

//Out put
array:1 [
  0 => Google_Service_Translate_Translation {#681 ▼
    +detectedLanguageCode: null
    #glossaryConfigType: "Google_Service_Translate_TranslateTextGlossaryConfig"
    #glossaryConfigDataType: ""
    +model: null
    +translatedText: "je suis un homme bon"
    #internal_gapi_mappings: []
    #modelData: []
    #processed: []
  }
]

Now you know how to translate text from one language to another using Google translation API. You can add as many language variations you want to add. If you are work on laravel and want to make multi-language, then you can check my post on Laravel multi-language site.