PHP code example of penobit / google-translate-php

1. Go to this page and download the library: Download penobit/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/ */

    

penobit / google-translate-php example snippets


use Penobit\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

$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 Penobit\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