禁止使用模板插件做违法内容(涉黄等),否则将受到法律的制裁。

阿里云机器翻译通用版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 个评论

 
联系
目前暂停一切业务,客服消息可能不会及时回复,谢谢理解。
在线咨询
    在线咨询
    禁止使用模板插件做违法内容(涉黄等),否则将受到法律的制裁。