Free Google Translate API PHP Package. Translates totally free of charge.
Install this package via Composer.
composer require stichoza/google-translate-php
Or edit your project's composer.json
to require stichoza/google-translate-php
and then run composer update
.
"require": {
"stichoza/google-translate-php": "~3.0"
}
Instantiate TranslateClient object
use Stichoza\GoogleTranslate\TranslateClient;
$tr = new TranslateClient('en', 'ka');
Or set/change languages later
$tr = new TranslateClient(); // Default is from 'auto' to 'en'
$tr->setSource('en'); // Translate from English
$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 static method
echo TranslateClient::translate('en', 'ka', 'Hello again');
To detect language automatically, just set the source language to null
$tr = new TranslateClient(null, 'es'); // Detect language and translate to Spanish
$tr->setSource(null); // Another way
Warning! This feature is experimental and works only for object calls (non-static).
$tr = new TranslateClient(null, 'fr');
$text = $tr->translate('Hello World!');
echo $tr->getLastDetectedSource(); // Output: en
Return value may be boolean FALSE
if there is no detected language.
Supported languages are listed in Google API docs.
Both static and non-static translate()
methods will throw following Exceptions:
InvalidArgumentException
If parameters are passed incorrectly.ErrorException
If the HTTP request fails for some reason.UnexpectedValueException
If data received from Google cannot be decoded.BadMethodCallException
If you call something wrong. Calltranslate()
, not Ghost Busters
In addition translate()
method will return boolean FALSE
if there is no translation available.
You can still view usage docs for older (~2.0
) versions here.
This package is developed for educational purposes only. Do not depend on this package as it may break anytime as it is based on "CURLing" the Google Translate website. Consider buying Official Google Translate API for other types of usage.