Using Google Translate in PHP

After Hacking Google Voice API, We are about to hack Google Translate this time! We are going to write a full featured yet basic class in php to help us use Google Translate. The best part is that it is going to be lightweight and dependency-free.

Let's start by defining properties for our GoogleTranslate class, let's think of it this way: we need a variable to hold the original language, another one to hold the language which we are translating to, a result holder and an extra one to hold the api url format, used in the curl request later.

<!--?php
class GoogleTranslate {
   public $lastResult = "";
   private $langFrom;
   private $langTo;
   private static $urlFormat = "http://translate.google.com/translate_a/t?client=t&text=%s&hl=en&sl=%s&tl=%s&ie=UTF-8&oe=UTF-8&multires=1&otf=1&pc=1&trs=1&ssel=3&tsel=6&sc=1";

The $LangFrom and $LangTo variable need setters, this is how we are going to do it

public function setLangFrom($lang) {
   $this->langFrom = $lang;
   return $this;
}
public function setLangTo($lang) {
   $this->langTo = $lang;
   return $this;
}

You may wonder why would I write return $this, which means that these two function will return a reference to the object after affecting the properties. This technique is called method chaining which enables us to make multiple calls for different methods in the same line. A good example would be helpful, let's see the class constructor

public function __construct($from = "en", $to = "fr") {
   $this->setLangFrom($from)->setLangTo($to);
}

This should be enough to setup parameters for the request. But we need a method that would actually trigger the connection. Things would be easier if we chose to use curl

public static final function makeCurl($url, array $params = array(), $cookieSet = false) {
   if (!$cookieSet) {
       $cookie = tempnam("/tmp", "CURLCOOKIE");
      $curl = curl_init($url);
      curl_setopt($curl, CURLOPT_COOKIEJAR, $cookie);
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
      curl_exec($curl);
   }   $queryString = http_build_query($params);
   $curl = curl_init($url . "?" . $queryString);
   curl_setopt($curl, CURLOPT_COOKIEFILE, $cookie);
   curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
   $output = curl_exec($curl);   return $output;
 }

The process is divided in two steps: a first call is done to retrieve cookies information (if given), then a second call to request real data using the previous cookies. If you are too impatient, you have probably tried the script at this stage, if you did, you would notice that it works! it only needs some filtering that is what the next method does

public function translate($string) {
   $url = sprintf(self::$urlFormat, rawurlencode($string), $this->langFrom, $this->langTo);
   $result = preg_replace('!,+!', ',', self::makeCurl($url)); // remove repeated commas (causing JSON syntax error)
   $resultArray = json_decode($result, true);
   return $this->lastResult = $resultArray[0][0][0];
 }

This method patches the placeholders in the $urlFormat, makes the request, cleans out the received data, decode it and extracts the main result from it. This is quite simple to figure out on your own, you just need to play with the real Google Translate page to know what to do. Now the class is ready and fully functional. Go ahead and create a new file in the same directory as the first one, write the following

<?php
include "GoogleTranslate.class.php";
$t = new GoogleTranslate('en', 'ar');
echo $t->translate("Hello World!");
?>

this would return

مرحبا العالم !

isn't this great! This was pretty easy and short. Go ahead and take a look at my gist, you will get the complete class assembled, with an extra method that i have included which can be called statically, having all the data as parameters, I will let you discover it on your own. If you find this tutorial useful, follow me here and on social networks to get updated for new tutorials.

Published: July 19 2013

blog comments powered by Disqus