龚哥哥 - 山里男儿 爱生活、做自己!
使用百度API翻译接口将网页翻译成英文
发表于 2020-8-31 | 浏览(21987) | PHP

将网页内容翻译成英文,或者更多语言

HTML代码

<!doctype html>
<head>
    <meta charset="utf-8" />
    <title>网页翻译测试</title>
</head>
<body>
    <div>测试
        <div>橘子</div>
    </div>
    <div>梨</div>
    <div>测试</div>
    <div>零食</div>
    <div>水果</div>
    <div>上班</div>
    <div>ShopXO 免费开源系统,可商用,可二次开发。</div>

    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js" type="text/javascript" charset="utf-8"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/blueimp-md5/2.17.0/js/md5.js"></script>
    <script type="text/javascript">
        function transformLanguage(newLanguage) {
            // 获取所有dom元素中文
            var transformStr = '';
            var temp_index = 0;
            // 获取所有dom元素
            function getChildDom(dom, type, data = {}) {
                if(type == 'read') {
                    [...dom.children].forEach(v => {
                        // 判断中文
                        // /^[\u0391-\uFFE5]+$/
                        var re= /[\u4e00-\u9fa5]/g;
                        // 防止某些标签有内容并且有标签 ,或者有空格 
                        var vHtml = $(v).contents().filter(function (index, content) {return content.nodeType === 3}).text().trim();
                        // 跳过script标签
                        if (re.test(vHtml) && v.tagName != 'SCRIPT') {
                            // 使用\n换行拼接、接口将返回数组
                            transformStr += `${vHtml}\n`
                        }
                        // 递归获取元素
                        getChildDom(v, type, data);
                    })
                }else {
                    [...dom.children].forEach(v => {
                        // 判断中文
                        // /^[\u0391-\uFFE5]+$/
                        var re= /[\u4e00-\u9fa5]/g;
                        var vHtml = $(v).contents().filter(function (index, content) {return content.nodeType === 3}).text().trim();
                        // 跳过script标签
                        if (re.test(vHtml) && v.tagName != 'SCRIPT') {
                            if((data[temp_index] || null) != null)
                            {
                                var transOld = data[temp_index]['src'];
                                var transNew = data[temp_index]['dst'];
                                // 防止标签里面还有标签,所以只替换里面的html,使用replace
                                $(v).html(
                                    $(v).html().replace( transOld, transNew)
                                )
                                temp_index++;
                            }
                        }
                        // 递归获取元素
                        getChildDom(v, type, data);
                    })
                }
            }
            getChildDom(document,'read');

            if((transformStr || null) != null)
            {
                getTranslateData();
                // 获取翻译
                // 接口申请地址 https://api.fanyi.baidu.com/
                function getTranslateData() {
                    var appid = '...';   // 百度翻译API的appid
                    var key = '...';   // 百度翻译API的key
                    var salt = (new Date).getTime();
                    var query = transformStr;
                    var from = 'zh';
                    var to = newLanguage;
                    var str1 = appid + query + salt + key;
                    var sign = md5(str1);
                    $.ajax({
                        url: 'baidu.php',
                        type: 'post',
                        dataType: 'json',
                        data: {
                            q: query,
                            appid: appid,
                            salt: salt,
                            from: from,
                            to: to,
                            sign: sign
                        },
                        success: function(data) {
                            data.trans_result && getChildDom(document,'write',data.trans_result);
                        }
                    });
                }
            }
        }

        // 页面加载完成再执行
        window.onload = function () {
            transformLanguage('en');
        };
    </script>
</body>

PHP代码

<?php

/**
 * curl
 * @author  Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2020-08-31
 * @desc    description
 * @param   [type]          $url     [description]
 * @param   [type]          $post    [description]
 * @param   boolean         $is_json [description]
 */
function CurlPost($url, $post, $is_json = false)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
    curl_setopt($ch, CURLOPT_URL, $url);

    // 是否 json
    if($is_json)
    {
        $data_string = json_encode($post);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                "Content-Type: application/json; charset=utf-8",
                "Content-Length: " . strlen($data_string)
            )
        );
    } else {
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                "Content-Type: application/x-www-form-urlencoded",
                "cache-control: no-cache"
            )
        );
    }

    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

echo CurlPost('http://api.fanyi.baidu.com/api/trans/vip/translate', $_POST);

阅读全文

TOP