Google Translate is one of the best tools on the internet that translates text to another language. Currently it supports 90+ languages. Google has its API for translate, but its not free and you have to go through a lot of procedures. It’s boring, right ? If your app/website needs a translator, this post will help you.
As you know Google Translate is a web app and you can monitor the requests it sends to the server. If you look through the Developer Tools during a translation process, you will get the URL !
I did this and made a Francium class called “Translator” (of course it is). You can see the GitHub project here.
It is not a big project (< 300 lines) and it has only 1 function to be used by you.
Requirements
Configuration
One thing to note is that, we don’t mention language by its full name. But, with short forms. You can find these short forms in the class file itself. It is an array in config
->languages
. Example :
There is only one sub config that you have to edit. It is `config`->`default`. What it contains is the default translation languages. Again, you have to use the short form of languages here. This is useful when you are going to use the translator for a single lang-to-lang translation.
Translate
Now, let’s translate something. Here is the syntax of \Fr\Translator::translate() :
\Fr\Translator::translate($text, $translateTo, $translateFrom);
If the $translateFrom is null, the value “auto” is used which means that Google will detect the language of the text.
And if $translateTo is null, the default value from `config`->`default` is used.
Examples
Translating “Hello” into Malayalam :
echo \Fr\Translator::translate("Hello", "ml", "en");
// Outputs "ഹലോ"
Translating “My House” to French :
echo \Fr\Translator::translate("Hello", "fr", "en");
// Outputs "Ma Maison"
Translating “Internet” to Arabic :
echo \Fr\Translator::translate("Hello", "ar", "en");
// Outputs "Ma Maison"
This Francium class supports error logging too. The most likely error you’re going to get will be of cURL‘s.
For support, you can see this page.