PHPackages                             themismin/google-translate-php - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. themismin/google-translate-php

ActiveLibrary[API Development](/categories/api)

themismin/google-translate-php
==============================

Free Google Translate API PHP Package

v1.0.0(2y ago)0145MITPHPPHP ^8.0

Since May 7Pushed 2y agoCompare

[ Source](https://github.com/themismin/google-translate-php)[ Packagist](https://packagist.org/packages/themismin/google-translate-php)[ Docs](https://github.com/themismin/google-translate-php)[ Fund](https://btc.com/bc1qc25j4x7yahghm8nnn6lypnw59nptylsw32nkfl)[ Fund](https://www.paypal.me/stichoza)[ RSS](/packages/themismin-google-translate-php/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (2)Versions (2)Used By (0)

Google Translate PHP
====================

[](#google-translate-php)

[![Latest Stable Version](https://camo.githubusercontent.com/8d3ba96136532500803bba48c63d3e52fe1b5630ff298083caa1acd0265ad650/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f53746963686f7a612f676f6f676c652d7472616e736c6174652d7068702e737667)](https://packagist.org/packages/stichoza/google-translate-php) [![Total Downloads](https://camo.githubusercontent.com/aa434638e5e1b3c4627ca261fe55419d257f542be0e6298f2abd6d10a2637a89/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f53746963686f7a612f676f6f676c652d7472616e736c6174652d7068702e737667)](https://packagist.org/packages/stichoza/google-translate-php) [![Downloads Month](https://camo.githubusercontent.com/cb9b7f13783b6e8ce25b7c2586fd9c30f128d2e8c0b8dd4cc0941a4a766244f0/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f646d2f53746963686f7a612f676f6f676c652d7472616e736c6174652d7068702e737667)](https://packagist.org/packages/stichoza/google-translate-php) [![Petreon donation](https://camo.githubusercontent.com/3566813b4190b2759b0439c2147228bec3a5a0f1ec6b7e0302305802431a7c3d/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f70617472656f6e2d646f6e6174652d6f72616e67652e737667)](https://www.patreon.com/stichoza) [![PayPal donation](https://camo.githubusercontent.com/b48a7f9ca978349b83c641e4901221d7e84374bcb3300a43f739835cf930e802/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f70617970616c2d646f6e6174652d626c75652e737667)](https://paypal.me/stichoza)

Free Google Translate API PHP Package. Translates totally free of charge.

---

- **[Installation](#installation)**
- **[Basic Usage](#basic-usage)**
- [Advanced Usage](#advanced-usage)
    - [Language Detection](#language-detection)
    - [Preserving Parameters](#preserving-parameters)
    - [Using Raw Response](#using-raw-response)
    - [Custom URL](#custom-url)
    - [HTTP Client Configuration](#http-client-configuration)
    - [Custom Token Generator](#custom-token-generator)
    - [Errors and Exception Handling](#errors-and-exception-handling)
- [Known Limitations](#known-limitations)
- [Disclaimer](#disclaimer)
- [Donation](#donation)

Installation
------------

[](#installation)

Install this package via [Composer](https://getcomposer.org/).

```
composer require stichoza/google-translate-php

```

> **Note****PHP 8.0 or later** is required. Use following versions of this package for older PHP versions:

Package versionPHP VersionDocumentation`^5.1`PHP &gt;= 8.0[v5 Docs](#google-translate-php)`^4.1`PHP &gt;= 7.1[v4 Docs](https://github.com/Stichoza/google-translate-php/tree/4.1#google-translate-php)`^3.2`PHP &lt; 7.1[v3 Docs](https://github.com/Stichoza/google-translate-php/tree/3.2#google-translate-php)Basic Usage
-----------

[](#basic-usage)

Create GoogleTranslate object

```
use Stichoza\GoogleTranslate\GoogleTranslate;

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

Or you can change languages later

```
$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
```

Translate sentences

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

Also, you can also use method chaining

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

Or call a shorthand static method `trans`

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

Advanced Usage
--------------

[](#advanced-usage)

### Language Detection

[](#language-detection)

To detect language automatically, just set the source language to `null`:

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

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

Use `getLastDetectedSource()` to get detected language:

```
$tr = new GoogleTranslate('fr');

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

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

Return value will be `null` if the language couldn't be detected.

Supported languages are listed in [Google API docs](https://cloud.google.com/translate/docs/languages).

### Preserving Parameters

[](#preserving-parameters)

The `preserveParameters()` method allows you to preserve certain parameters in strings while performing translations. This is particularly useful when dealing with localization files or templating engines where specific placeholders need to be excluded from translation.

Default regex is `/:(\w+)/` which covers parameters starting with `:`. Useful for translating language files of Laravel and other frameworks. You can also pass your custom regex to modify the parameter syntax.

```
$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
```

Or use custom regex:

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

You can use same feature with static `trans()` method too.

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

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

### Using Raw Response

[](#using-raw-response)

For advanced usage, you might need the raw results that Google Translate provides. you can use `getResponse` method for that.

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

### Custom URL

[](#custom-url)

You can override the default Google Translate url by `setUrl` method. Useful for some countries

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

### HTTP Client Configuration

[](#http-client-configuration)

This package uses [Guzzle](https://github.com/guzzle/guzzle) for HTTP requests. You can pass an array of [guzzle client configuration options](http://docs.guzzlephp.org/en/latest/request-options.html) as a third parameter to `GoogleTranslate` constructor, or just use `setOptions` method.

You can configure proxy, user-agent, default headers, connection timeout and so on using this options.

```
$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');
```

For more information, see [Creating a Client](http://guzzle.readthedocs.org/en/latest/quickstart.html#creating-a-client) section in Guzzle docs.

### Custom Token Generator

[](#custom-token-generator)

You can override the token generator class by passing a generator object as a fourth parameter of constructor or just use `setTokenProvider` method.

Generator must implement `Stichoza\GoogleTranslate\Tokens\TokenProviderInterface`.

```
use Stichoza\GoogleTranslate\Tokens\TokenProviderInterface;

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

And use:

```
$tr->setTokenProvider(new MyTokenGenerator);
```

### Translation Client (Quality)

[](#translation-client-quality)

Google Translate has a parameter named `client` which defines quality of translation. First it was set to `webapp` but later google added `gtx` value which results in a better translation quality in terms of grammar and overall meaning of sentences.

You can use `->setClient()` method to switch between clients. For example if you want to use older version of translation algorithm, type `$tr->setClient('webapp')->translate('lorem ipsum...')`. Default value is `gtx`.

### Errors and Exception Handling

[](#errors-and-exception-handling)

Static method `trans()` and non-static `translate()` and `getResponse()` methods will throw following exceptions:

- `ErrorException` If the HTTP request fails for some reason.
- `UnexpectedValueException` If data received from Google cannot be decoded.

As of **v5.1.0** concrete exceptions are available in `\Stichoza\GoogleTranslate\Exceptions` namespace:

- `LargeTextException` If the requested text is too large to translate.
- `RateLimitException` If Google has blocked you for excessive amount requests.
- `TranslationRequestException` If any other HTTP related error occurs during translation.
- `TranslationDecodingException` If the response JSON cannot be decoded.

All concrete exceptions are backwards compatible, so if you were using older versions, you won't have to update your code.

`TranslationDecodingException` extends `UnexpectedValueException`, while `LargeTextException`, `RateLimitException` and `TranslationRequestException` extend `ErrorException` that was used in older versions (`
