Thursday, February 10, 2011

Google Language translation for large Text

Create a below function and Apply the function to the text or fields which need to be translated to the destination language

googleTranslateTool.class.php
<?php
class Google_Translate_API {
 function translate($text, $from = '', $to = 'en') {
  $url = 'http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q='.rawurlencode($text).'&langpair='.rawurlencode($from.'|'.$to);
  $response = file_get_contents(
   $url,
   null,
   stream_context_create(
    array(
     'http'=>array(
     'method'=>"GET",
     'header'=>"Referer: http://%22.$_server['http_host'].%22//r/n"
     )
    )
   )
  );
  if (preg_match("/{\"translatedText\":\"([^\"]+)\"/i", $response, $matches)) {
   return self::_unescapeUTF8EscapeSeq($matches[1]);
  }
  return false;
 }

 function _unescapeUTF8EscapeSeq($str) {
  return preg_replace_callback("/\\\u([0-9a-f]{4})/i", create_function('$matches', 'return html_entity_decode(\'&#x\'.$matches[1].\';\', ENT_NOQUOTES, \'UTF-8\');'), $str);
 }
}
?>


Create the page which need to be translated

<?php
require_once('googleTranslateTool.class.php');
$text = 'Hello I am testing translation Hello I am testing translation Hello I am testing translation Hello I am testing translation Hello I am testing translation Hello I am testing translation Hello I am testing translation Hello I am testing translation Hello I am testing translation';
$strlen = strlen($text);
if($strlen<=500){
  $ttext = $text;
}else{
 
  $mi = ceil($strlen/1500);
  for($i=0; $i<$mi; $i++)
  {
    $ttext = substr($text,1500*i,1499);
    $trans_text = Google_Translate_API::translate($ttext, '', 'en');
    if ($trans_text !== false) {
   $trn_text=$trn_text.$trans_text;
   }else{
     $trn_text=$trn_text.$text;
   }
  }
}
echo $trn_text;
?>

1 comment:

  1. Impressive web site, Distinguished feedback that I can tackle. Im moving forward and may apply to my current job as a pet sitter, which is very enjoyable, but I need to additional expand. Regards. תרגום לשפה ספרדית

    ReplyDelete