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

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


前言

讯飞星火API笔者试用后感觉还不错,遂推荐给大家,以飨开发者。

一、讯飞开放平台有什么?

星火认知大模型、语音识别、语音合成、语音扩展、自然语言处理、文字识别、图像识别等。

二、使用步骤

1.注册并认证

访问讯飞官网注册账号:https://xinghuo.xfyun.cn/sparkapi?ch=gji
在这里插入图片描述
服务管理-完成个人认证
在这里插入图片描述

2.创建应用

右上角-我的应用
在这里插入图片描述
完善应用信息
在这里插入图片描述
左边选择“机器翻译”
在这里插入图片描述
右边的token信息需要记录下来
实时用量-购买字符量-免费领取
在这里插入图片描述

3.构建API

https://www.xfyun.cn/doc/nlp/xftrans/API.html
官网提供的demo有python3、java、nodejs、php、go语言
这里以PHP为例构建一个API

<?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。

4.调用实例

请求地址:

https:/你的api地址/?text=hello,world&from=en&to=cn

返回数据:

{
   "code": "200",
   "src": "hello,world",
   "dst": "你好,世界"
}

Demo:https://api.szfx.top/api/xftrans.html


总结

以上就是使用PHP借助讯飞机器翻译构建API的教程,欢迎大家去体验。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值