Friday, July 31, 2009

Google translate simple php client

This morning i were reading an english based blog. I came from italy and (as you can notice) im not the best english speller at all. Sometimes i need to use an online dictionary to translate words or sentences. One of the most dictionary translation is and also
Well im a web programmer, google offers a rich api to its services, so i thought to write a really simple php batch to translate words or simple sentence.

here a snippet:


if($argc < 4) die("usage: gt.php \"sentence\" <start lang> <translation lang>");

$sentence = urlencode($argv[1]);
$start = $argv[2];
$arrive = $argv[3];

$url = "$sentence&langpair=$start%7C$arrive";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, "");
$body = curl_exec($ch);

$json = json_decode($body);

if(!is_null($json->responseDetails)) { die($json->responseDetails); }

echo $json->responseData->translatedText;

Hope someone could find this useful. You can call it as the follow:
gt.php "sentence or words" <strat> <translate>

Have fun =) !