zoukankan      html  css  js  c++  java
  • php 翻译对接api

    在跨境工作中我们经常遇到语言之间的转换的问题,现在我推荐两个通过php代码对接接口实现翻译功能:

    一.谷歌翻译(推荐)   

    因为这个不需要注册什么账号,获取sign等api的信息,这个也比较好用,所以推荐使用。

         $str = 'hello world!';
            $str = htmlspecialchars($str, ENT_NOQUOTES);
            $ret = array();
            $length = 5210;  //这是长度,可能因为内容太长导致翻译返回为空,所以这里可以采用截取字符长度的方法来进行翻译
            $len = mb_strlen($str, "UTF-8");
            $fanyi = "";
            for ($i = 0; $i < $len; $i += $l) {
                $fanyi .= $this->gtranslate(mb_substr($str, $i, $l, "UTF-8"));
            }

         echo $fanyi;
    
    
    function gtranslate($text)
    {
    $entext = urlencode($text);
    $url = 'http://translate.google.cn/translate_a/single?client=gtx&dt=t&ie=UTF-8&oe=UTF-8&sl=auto&tl=zh-CN&q=' . $entext;
    set_time_limit(0);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 20);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 40);
    curl_setopt($ch, CURLOPT_URL, $url);
    $result = curl_exec($ch);
    curl_close($ch);
    $result = json_decode($result);
    if (!empty($result)) {
    foreach ($result[0] as $k) {
    $v[] = $k[0];
    }
    return implode(" ", $v);
    }
    }
     

    二,百度翻译

     $appid = "20200612000****"; //您注册的API Key
            $key = "0LRoMVHVLJlR**********"; //密钥
            $from = 'en';
            $to = "zh";
            $salt = rand(1000000000, 9999999999); //随机数
            $sign = md5($appid . $value_code . $salt . $key); //签名
            $value_code = urlencode($value_code);
            //生成翻译API的URL
            $languageUrl = "http://api.fanyi.baidu.com/api/trans/vip/translate?q=$value_code&appid=$appid&salt=$salt&from=$from&to=$to&sign=$sign";
            $text = json_decode($this->language_text($languageUrl));
    
    
    function language_text($reqURL)
    {
        $ch = curl_init($reqURL);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch);
        if ($result) {
            curl_close($ch);
            return $result;
        } else {
            $error = curl_errno($ch);
            curl_close($ch);
            return ("curl出错,错误码:$error");
        }
    }
     
  • 相关阅读:
    k8s 节点的 NodeAffinity 使用
    template 与 host , item trigger的关系
    mysql 性能优化思路
    nginx 配sorry page
    修改tomcat JVM 大小 jdk--目录修改
    (转)MySQL慢查询分析优化 + MySQL调优
    注册表操作 Microsoft.Win32.Registry与RegistryKey类
    C#(99):WCF之.NET Remoting通讯
    CallContext线程数据缓存-调用上下文
    C#(99):JSON与对象的序列化与反序列化
  • 原文地址:https://www.cnblogs.com/kobigood/p/13100891.html
Copyright © 2011-2022 走看看