PHP code example of stichoza / google-translate-php

1. Go to this page and download the library: Download stichoza/google-translate-php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

stichoza / google-translate-php example snippets


use Stichoza\GoogleTranslate\GoogleTranslate;

$tr = new GoogleTranslate('en'); // Translates into English

$tr = new GoogleTranslate(); // Translates to 'en' from auto-detected language by default
$tr->setSource('en'); // Translate from English
$tr->setSource(); // Detect language automatically
$tr->setTarget('ka'); // Translate to Georgian

echo $tr->translate('Hello World!');

echo $tr->setSource('en')->setTarget('ka')->translate('Goodbye');

echo GoogleTranslate::trans('Hello again', 'ka', 'en');

$tr = new GoogleTranslate('es', null); // Or simply do not pass the second parameter 

$tr->setSource(); // Another way

$tr = new GoogleTranslate('fr');

$text = $tr->translate('Hello World!');

echo $tr->getLastDetectedSource(); // Output: en

$tr = new GoogleTranslate('de');

$text = $tr->translate('Page :current of :total'); // Seite :aktuell von :gesamt

$text = $tr->preserveParameters()
           ->translate('Page :current of :total'); // Seite :current von :total

$text = $tr->preserveParameters('/\{\{([^}]+)\}\}/')
           ->translate('Page {{current}} of {{total}}'); // Seite {{current}} von {{total}}

GoogleTranslate::trans('Welcome :name', 'fr', preserveParameters: true); // Default regex

GoogleTranslate::trans('Welcome {{name}}', 'fr', preserveParameters: '/\{\{([^}]+)\}\}/'); // Custom regex

$responseArray = $tr->getResponse('Hello world!');

$tr->setUrl('http://translate.google.cn/translate_a/single'); 

$tr = new GoogleTranslate('en', 'ka', [
    'timeout' => 10,
    'proxy' => [
        'http'  => 'tcp://localhost:8125',
        'https' => 'tcp://localhost:9124'
    ],
    'headers' => [
        'User-Agent' => 'Foo/5.0 Lorem Ipsum Browser'
    ]
]);

// Set proxy to tcp://localhost:8090
$tr->setOptions(['proxy' => 'tcp://localhost:8090'])->translate('Hello');

// Set proxy to socks5://localhost:1080
$tr->setOptions(['proxy' => 'socks5://localhost:1080'])->translate('World');

use Stichoza\GoogleTranslate\Tokens\TokenProviderInterface;

class MyTokenGenerator implements TokenProviderInterface
{
    public function generateToken(string $source, string $target, string $text): string
    {
        // Your code here
    }
}

$tr->setTokenProvider(new MyTokenGenerator);

composer