snippet

 

类定义

 

/**

* Google翻译的ajax接口简单封装

*/

class GoogleTranslateAjaxAPI {

 

/**

* 调用Google翻译ajax接口,直接返回

*/

public static function translate($content, $fromLang = \'zh-CN\', $toLang = \'en\', $fromEnc = \'UTF-8\', $toEnc = \'UTF-8\') {

try {

// 因为是通过URL传递参数,需要编码,还可能存在长度限制

$content = trim($content);

$content = urlencode($content);

$url = "http://translate.google.cn/translate_a/t?client=t&sl=$fromLang&tl=$toLang&hl=en&sc=2&ie=$fromEnc&oe=$toEnc&oc=1&otf=2&srcrom=1&ssel=5&tsel=5&q=$content";

$html = file_get_contents($url);

} catch (Exception $ex) {

$html = \'\';

}

return $html;

}

}

 

使用示例

 

/**

* 获取客户端提交数据

*/

function getRequest($key, $default = null) {

return isset($_REQUEST[$key]) ? $_REQUEST[$key] : $default;

}

 

/**

* 页面入口函数

*/

function main() {

header("Content-type: text/html; charset=utf-8");

$fromLang = getRequest(\'fromLang\', \'zh-CN\');

$toLang = getRequest(\'toLang\', \'en\');

$fromEnc = getRequest(\'fromEnc\', \'UTF-8\');

$toEnc = getRequest(\'toEnc\', \'UTF-8\');

$content = getRequest(\'content\', \'测试\');

$googleret = GoogleTranslateAjaxAPI::translate($content, $fromLang, $toLang, $fromEnc, $toEnc);

return $googleret;

}

 

echo main();

 

前端JS

    $.get(url, {toLang: toLang, content: inputContent}, function(data){
        // 由于调用了Google翻译的ajax接口,此处data格式为Google定义格式
        var data = new Function("return " + data)();
        var sentences = [],
            i = 0, len = data[0].length;
        // 合并每一个句子中的目标翻译对象
        for(i = 0, len = data[0].length; i<len; i++) {
            sentences.push(data[0][i][0]);
        }
        // 替换到文本输入框中
        $(\'#output\').val(sentences.join(\' \'));
    }, \'text\');

 

 

 

分类:

技术点:

相关文章: