How to translate Dynamic Texts into any Language

How to translate Dynamic Texts into any Language

In this Blog, we describe that how we can translate any dynamic data into different languages.

How to translate Dynamic Texts into any Language

This is a free Google Translate API PHP Package that translates free of charge.

Step 1: Install the Given composer package using Terminal

composer require stichoza/google-translate-php

Note:  PHP 7.1 or later is required. For older versions, use ^3.2 version of this package

 

Step 2: Use the Below code in your controller

use Stichoza\GoogleTranslate\GoogleTranslate;

$lang = "fr" // This will translate into English 
//For english use "en", For Hindi use "hi", for French use "fr", for gujrati use "guj" 

$trans = new GoogleTranslate($lang);
$title = "Hello";
$data = $trans->translate($title);

echo $data;   // this will return "hello" into French language

Other: Advance Examples ( Increase Speeding of translation)

If you have so much Dynamic data, you can face slow speed. It can take almost 5-10 seconds to translate significant texts. To overtake this problem use Redis or any other caching backends.

Note: If you want to learn about Redis then read our blog for Redis confguration. Here is the link, https://softtechover.com/post/how-to-use-redis-into-laravel-using-predis-package 

Now, use the below code for caching.

//get cached translated data
function getTransData($title,$lang)
{
    $redis = Redis::connection();
    $setting = Redis::get($title.'_'.$lang);

    if (isset($setting) && $setting != null) {
        return $setting;   // This will return translated data from cached in very quick time
    } else {
        $trans = new GoogleTranslate($lang);
        $titles = $trans->translate($title);
        Redis::set($title.'_'.$lang , $titles);
        return $titles;  // This will return Translated data for very First time
    }
}

// Don't forget to start redis server before using this code

Now, This package translates any data in a very quick time in any language.