PHP translate function using google
When you write those multiple language websites you have to make sure everything can be translated. Even the user interface. And this is most of the time something we overlook or you use icons instead.
In this tutorial I show you a nice translation function. And if you do not know any translation for that specific word. It will look it up on Google translate!
What can you do with it?
Well in the end you will be able to write code like this.
echo TL::T("Hello");
Depending on the current language it will print Hello World in that specific language.
Practical example?
Form validation. When you print errors to the user interface it is just more easy to use this function.
If ($name == "") {
echo TL::T("Please fill in your name");
}
How will it work?
We create a database table that can contain translations for specific languages.
When you call the TL::T function it will lookup the parsed text in the databases English translation. (If you program in another language you can change this of course but just make sure you always parse to TL::T in the same language)
When it did not found a English translation it will create a record for it.
If the current language is not English and it did found a record with the English translation it will check if there is a translation in the same record for the current language. If that is not the case it will translate the English word to the specified language through Google translate.
Why not always' Google translate?
Because Google translate is not fail proof. Sometimes it will give strange translations. Especially when you try to translate full sentences. But instead there is a strange language message in your interface it gives you an almost correct translation. If you find a better translation you can put that into your database and boom. You will get this translation instead of Google's.
Step 1: building the database:
First of all you need a database table to store all translations.
In this example lets create 4 languages.
English = en, French = fr, German = de and Dutch = nl
Name your fields en, fr, de and nl.
call your table tbltrans.
Step 2: building the TL static class:
Why do we call this class TL? Well it is short. you can call it TRANSLATE and then use a function like WORD so you have to type TRANSLATE::WORD() all the times. So no. we want to code quickly and call it TL.
class TL
{
}
Notice that these static functions are shorthands to get $_SESSION vars. And if it is not set it will return false.
Usage:
TL::SS('LANG', 'nl'); Will set our LANG session var to nl.
We will use this LANG session as our current language identifier.
Step 3: our Google translate function
Add this function to the TL class.


