Google translate script

2010-01-18
2013-04-24
  • Andrzej Kmicic
    Andrzej Kmicic
    2010-01-18

    Script for translate text from any selected lang to any selected language.
    Text to translate is in first tab of Notepad++ :

    <?php
        nppUserCommand("NPPM_ACTIVATEDOC",0,0); 
        // activate first view and first document
        $logtxt = sciGetText();
        // get text from active document text
        $logtxt=nl2br($logtxt);
        $base_url="http://www.google.com/uds/Gtranslate";
        $l_from="en"; 
        // translate language from
        $l_to="pl";   
        // translate language to
        $url="$base_url?v=1.0&key=notsupplied&q=".
        urlencode($logtxt)."&langpair=".$l_from. "|" .$l_to;
        $contents=file_post_contents($url);
        $json = json_decode($contents, true); 
        if($json{'responseStatus'} == 200) 
        print preg_replace("#<br\s*?/?>#si","
    ", $json{'responseData'}{'translatedText'}); 
        else
        print "Error Response status:{$json{'responseStatus'}},".
        " details: {$json{'responseDetails'}}";
    function file_post_contents($url,$remove_headers=true) {
        $url = parse_url($url); 
        if (!isset($url{'port'})) {
          if ($url{'scheme'} == 'http') { $url{'port'}=80; }
          elseif ($url{'scheme'} == 'https') { $url{'port'}=443; }
        }
        $url{'query'}=isset($url{'query'})?$url{'query'}:'';
        $url{'protocol'}=$url{'scheme'}.'://';
        $eol="\r\n";
        $headers =  "POST ".$url{'protocol'}.$url{'host'}.$url{'path'}." HTTP/1.0".$eol. 
                    "Host: ".$url{'host'}.$eol. 
                    "Referer: ".$url{'protocol'}.$url{'host'}.$url{'path'}.$eol. 
                    "Content-Type: application/x-www-form-urlencoded".$eol. 
                    "Content-Length: ".strlen($url{'query'}).$eol.
                    $eol.$url{'query'};
        $fp = fsockopen($url{'host'}, $url{'port'}, $errno, $errstr, 30); 
        if($fp) {
          fputs($fp, $headers);
          $result = '';
          while(!feof($fp)) { $result .= fgets($fp, 128); }
          fclose($fp);
          if ($remove_headers) {
            //removes headers
            $pattern="/^.*\r\n\r\n/s";
            $result=preg_replace($pattern,'',$result);
          }
          return $result;
        }
    }
    ?>