PHP code:
Copy codeThe Code is 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, $ );
Preg_match_all ('/<span/s + title/= "[^>] +> ([^ <] +) </span>/I', $ gphtml, $ res );
$ This-> out = $ res [1] [0];
Return $ this-> out;
}
/*
$ From language to be translated
$ To translation language
*/
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, which is useless here.
* Langpair-src lang to dest lang
* How is the ie-urlencode encoded?
* Text-the text to be translated
*/
$ 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 ['fromla'])? $ _ REQUEST ['fromlanc']: 'en ';
$ To =! Empty ($ _ REQUEST ['internet'])? $ _ REQUEST ['internet']: '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, $ );
Echo "----------- translation result --------------/n ";
Echo iconv ('gbk', 'utf-8', $ g-> out );
Echo "/n ";
?>
2. Save the above content in a file named "gtranslate.
3. Add execution permissions to gtranslate
Chmod a + x gtranslate
4. Create a soft connection
Ln-s/yourpath/gtranslate/usr/bin/gtranslate
5. Enter the test Vocabulary:
Gtranslate Hello World
----------- Translation result --------------
Hello World
>>>
6. A Chinese/English Version is provided.
Use gtranslate China, English to Chinese
Gtranslate-r China
>>>