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");
        }
    }
     
  • 相关阅读:
    Shiro使用Redis作存储之后更新Session失败的问题
    安装JDK 9 时出现“正在进行另一Java安装”
    Rancher——新一代智障Docker调度系统
    使用Spring STOMP时ChannelInterceptor无法获取用户信息
    Docker生存要点
    多线程编程几个误区
    shiro中JdbcRealm使用salt的问题
    通过ProxyServlet实现可编程的反向代理
    关于之前的博客《SharePoint无代码工作流设计开发实例——交通费报销流程(三) 》的一些问题的解答
    SharePoint无代码工作流设计开发实例——交通费报销流程(三)
  • 原文地址:https://www.cnblogs.com/kobigood/p/13100891.html
Copyright © 2011-2022 走看看