zoukankan      html  css  js  c++  java
  • [PHP]Google翻译ajax接口简单封装

    类定义

    /**

    * 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');
  • 相关阅读:
    vim编辑器替换以及全局替换
    Linux下grep显示前后几行信息
    Pymol里常用到的命令,随用随记
    硬盘里有文件错误,导致删除不了文件,可以使用如下方法
    解决Host key verification failed
    tcl语言杂记
    python脚本后台运行的几种方式
    centos设置连续登录3次密码错误自动锁定账户3分钟
    ubuntu安装显卡驱动
    虚拟交换机(OVS)之结构印象
  • 原文地址:https://www.cnblogs.com/snippet/p/3644227.html
Copyright © 2011-2022 走看看