PHP Code:
Copy Code code as follows:
#!/usr/bin/php-q
<?php
/**
* PHP Script for Google Translate
* @author: Yishan Wang
* @version: 1.0.0
*/
Class Google_api_translator
{
Public $url = "http://translate.google.com/translate_t";
Public $text = "";
Public $out = "";
Public $ip = ';
function SetText ($text) {
$this->text = $text;
}
function translate ($from = ' auto ', $to = ' zh-cn ') {
$this->out = "";
$gphtml = $this->postpage ($this->url, $this->text, $from, $to);
Preg_match_all ('/<span/s+title/= ' [^>]+> ([^<]+) <//span>/i ', $gphtml, $res);
$this->out = $res [1][0];
return $this->out;
}
/*
$from languages that need to be translated
The language of $to translation
*/
function Postpage ($url, $text, $from = ' auto ', $to = ' zh-cn ') {
$html = ';
if ($url!= "" && $text!= "") {
$ch = Curl_init ($url);
curl_setopt ($ch, Curlopt_returntransfer, 1);
if (!empty ($this->ip) && is_string ($this->ip)) {
curl_setopt ($ch, Curlopt_interface, $this->ip);
}
curl_setopt ($ch, Curlopt_header, 1);
curl_setopt ($ch, curlopt_followlocation, 1);
curl_setopt ($ch, Curlopt_timeout, 15);
/*
*HL-Interface language is useless here.
*langpair-src Lang to dest Lang
*ie-urlencode's Coding method?
*text-Text to translate
*/
$fields = Array (' HL=ZH-CN ', ' langpair= '. $from. ' | ') $to, ' ie=utf-8 ', ' text= '. $text);
$fields = Implode (' & ', $fields);
curl_setopt ($ch, Curlopt_post, 1);
curl_setopt ($ch, Curlopt_postfields, $fields);
$html = curl_exec ($ch);
if (Curl_errno ($ch)) $html = "";
Curl_close ($ch);
}
return $html;
}
}
$from =!empty ($_request[' Fromlan ')? $_request[' Fromlan ']: ' en ';
$to =!empty ($_request[' Tolan ')? $_request[' Tolan ']: ' ZH-CN ';
$keywords = "";
for ($i =1; $i < $ARGC; $i + +) {
$keywords. = $argv [$i]. " ";
}
$article =!empty ($_request[' article '])? $_request[' article ': $keywords;
$g = new Google_api_translator ();
if (isset ($_request[' IP ')) &&!empty ($_request[' IP '))
{
$g-> IP = $_request[' IP '];
}
$article = Iconv (' GBK ', ' UTF-8 ', $article);
$article = Str_replace (' {enter} ', '/r/n ', $article);
$g->settext ($article);
$g->translate ($from, $to);
echo "-----------translation results--------------/n";
echo iconv (' GBK ', ' UTF-8 ', $g->out);
echo "/n";
?>
2, the above content to save the name "Gtranslate" in the file.
3. Add execution rights to Gtranslate
chmod a+x Gtranslate
4. Create Soft Connection
Ln-s/yourpath/gtranslate/usr/bin/gtranslate
5, Input Test vocabulary:
Gtranslate Hello World
-----------Translation Results--------------
Hello World
>>>
6, made a bilingual version of the translation.
Using Gtranslate China, English to Chinese translation
With Gtranslate-r China, Chinese to English
>>>