wordpress收费下载资源主题
wordpress付费下载资源插件

阿里云机器翻译通用版PHP使用Demo

最近模板兔给一个客户做Ai绘画小程序,需要用到自动翻译,一开始用百度的接口,但是但是百度接口在某种情况下有Bug,所以转用了阿里云的接口,下面简单说一下如何使用阿里云机器翻译API。

SDK安装

composer require alibabacloud/sdk

比如你的项目目录是app,那么可以在宝塔里对app目录进行composer安装,安装完成后会自动生成一个vendor文件夹,然后接着引用即可。

Github地址是github.com/aliyun/openapi-sdk-php

代码示例

require __DIR__ . '/vendor/autoload.php';
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;

require_once(dirname(__FILE__)."/../wp-load.php");
$status = 0;$msg = '';$en = '';
$word = isset($_GET['word'])?$_GET['word']:'';
$word = str_replace(",",",",$word);
if($word){
if(!preg_match('/[\x{4e00}-\x{9fa5}]/u', $word)>0){
$status = 1;
$en = $word;
}else{
// 创建一个全局客户端
AlibabaCloud::accessKeyClient('your id', 'your secret')
->regionId('cn-hangzhou')
->asGlobalClient();

try {
$result = AlibabaCloud::alimt()
->v20181012() //通用版本
->translateGeneral()
->method('POST') //设置请求POST
->withSourceLanguage('zh') //源语言
->withSourceText($word) //原文
->withFormatType('text') //翻译文本的格式
->withTargetLanguage('en') //目标语言
->request();

$en= $result->toArray()['Data']['Translated'];
$status = 1;
} catch (ServerException $e) {
$msg = $e->getErrorMessage();
} catch (ClientException $e) {
$msg = $e->getErrorMessage();
}
}
}

0 个评论

定制开发
本站承接WordPress等系统建站仿站、二次开发、主题插件定制等开发服务
在线咨询
  • 请直接说明需求,勿问在否
    QQ:1-247-246-247

  • QQ一群:104228692(满)
  • QQ二群:64786792
在线咨询
本站承接WordPress建站仿站、二次开发、主题插件定制等PHP开发服务!

了解详情