前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >科大讯飞机器翻译接口PHP版API接入

科大讯飞机器翻译接口PHP版API接入

原创
作者头像
技术松鼠
修改2024-05-16 08:00:19
941
修改2024-05-16 08:00:19

1.获取KEY

左边选择“机器翻译”

右边的token信息需要记录下来
右边的token信息需要记录下来

2.构建API

这里以PHP为例构建一个API

代码语言:php
复制
<?php
/**
 * 机器翻译 WebAPI 接口调用示例
 * 运行前:请先填写Appid、APIKey、APISecret
 * 
 * 1.接口文档(必看):https://www.xfyun.cn/doc/nlp/xftrans/API.html
 * 2.错误码链接:https://www.xfyun.cn/document/error-code (错误码code为5位数字)
 * @author iflytek
 */
class Its_test {
    function tocurl($url, $header, $content){
        $ch = curl_init();
        if(substr($url,0,5)=='https'){
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
            curl_setopt($ch, CURLOPT_SSLVERSION, 1);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        if (is_array($header)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        curl_setopt($ch, CURLOPT_POST, true);
        if (!empty($content)) {
            if (is_array($content)) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($content));
            } else if (is_string($content)) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
            }
        }
        $response = curl_exec($ch);
        $error=curl_error($ch);
        //var_dump($error);
        if($error){
            die($error);
        }
        $header = curl_getinfo($ch);

        curl_close($ch);
        $data = array('header' => $header,'body' => $response);
        return $data;
    }
    function xfyun($text,$from,$to) {
    //在控制台-我的应用-机器翻译获取
        $app_id = "XXXXXXXXX";
    //在控制台-我的应用-机器翻译获取
        $api_sec = "XXXXXXXXX";
    //在控制台-我的应用-机器翻译获取
        $api_key = "XXXXXXXXX";
    // 机器翻译接口地址
        $url = "https://itrans.xfyun.cn/v2/its";

        //body组装
        //$text = "中华人民共和国于1949年成立";//待翻译文本
        $body = json_encode($this->getBody($app_id, $from,$to, $text));

        // 组装http请求头
        $date =gmdate('D, d M Y H:i:s') . ' GMT';

        $digestBase64  = "SHA-256=".base64_encode(hash("sha256", $body, true));
        $builder = sprintf("host: %s
date: %s
POST /v2/its HTTP/1.1
digest: %s", "itrans.xfyun.cn", $date, $digestBase64);
        // echo($builder);
        $sha = base64_encode(hash_hmac("sha256", $builder, $api_sec, true));

        $authorization = sprintf("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", $api_key,"hmac-sha256",
            "host date request-line digest", $sha);

        $header = [
            "Authorization: ".$authorization,
            'Content-Type: application/json',
            'Accept: application/json,version=1.0',
            'Host: itrans.xfyun.cn',
            'Date: ' .$date,
            'Digest: '.$digestBase64
        ];
        $response = $this->tocurl($url, $header, $body);

        // var_dump($response['body']);
        
        $res = json_decode($response['body'], true);//转换为数组
        header("content-type: application/json");
        $json_return = array(
            "code" => "200",
            "src" => $text,
            "dst" => $res['data']['result']['trans_result']['dst']
        );
        echo json_encode($json_return, JSON_UNESCAPED_UNICODE);
    }

    function getBody($app_id, $from, $to, $text) {
        $common_param = [
            'app_id'   => $app_id
        ];

        $business = [
            'from' => $from,
            'to'   => $to,
        ];

        $data = [
            "text" => base64_encode($text)
        ];

        return $body = [
            'common' => $common_param,
            'business' => $business,
            'data' => $data
        ];
    }
}

header('Access-Control-Allow-Origin:*');
header('Content-type: application/json');
$text=isset($_GET['text'])? $_GET['text'] :null; 
if(empty($text)){die("请传入text参数");}

$from=isset($_GET['from'])? $_GET['from'] :null; 
if(empty($from)){die("请传入源语言from参数");}

$to=isset($_GET['to'])? $_GET['to'] :null; 
if(empty($to)){
    if (preg_match("/([\x81-\xfe][\x40-\xfe])/", $text, $match)) {
        //含有汉字
        $to = 'en';
    } else {
        //不含有汉字
        $to = 'cn';
    }
}

$a = new Its_test();
$a->xfyun($text,$from,$to);

运行前:请先填写Appid、APIKey、APISecret。

3.调用实例

请求地址:

代码语言:txt
复制
https:/你的api地址/?text=hello,world&from=en&to=cn

返回数据:

代码语言:json
复制
{
   "code": "200",
   "src": "hello,world",
   "dst": "你好,世界"
}

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1.获取KEY
  • 2.构建API
  • 3.调用实例
相关产品与服务
机器翻译
机器翻译(Tencent Machine Translation,TMT)结合了神经机器翻译和统计机器翻译的优点,从大规模双语语料库自动学习翻译知识,实现从源语言文本到目标语言文本的自动翻译,目前可支持十余种语言的互译。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档