之前的阿里云SDK翻译接口:ThinkPHP对接阿里云翻译API接口
1、首先composer下载阿里云的SDK 2.0,

2、在阿里云线上SDK跑通,然后复制下来,改改代码,就完了:
use AlibabaCloud\SDK\Alimt\V20181012\Alimt;
use \Exception;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Alimt\V20181012\Models\TranslateGeneralRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
class Index extends Base
{
public static function createClient(){
// 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
// 建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/311677.html。
$config = new Config([
// 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
"accessKeyId" =>'LTAI5tCifAJhD4p4QvQ3H',
// 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
"accessKeySecret" => 'J1O97UuYmCdgWZWpuVQEWwcMP1'
]);
// Endpoint 请参考 https://api.aliyun.com/product/alimt
$config->endpoint = "mt.cn-hangzhou.aliyuncs.com";
return new Alimt($config);
}
/**
* @param string[] $args
* @return void
*/
public function main($id,$text){
$client = self::createClient();
$translateGeneralRequest = new TranslateGeneralRequest([
"formatType" => "text",
"sourceLanguage" => "en",
"targetLanguage" => "it",
"sourceText" => $text,
"scene" => "general"
]);
$runtime = new RuntimeOptions([]);
try {
// 复制代码运行请自行打印 API 的返回值
$result=$client->translateGeneralWithOptions($translateGeneralRequest, $runtime);
//print_r($result);
Db::name('product')->where('id',$id)->update(['info'=>$result->body->data->translated]);
echo $id;
echo '<br>';
}
catch (Exception $error) {
if (!($error instanceof TeaError)) {
$error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
}
// 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
// 错误 message
var_dump($error->message);
// 诊断地址
var_dump($error->data["Recommend"]);
Utils::assertAsString($error->message);
}
}
public function t(){
$data=Db::name('product')->select()->toArray();
foreach($data as $k=>$v){
if(!empty($v['info'])){
// $this->main($v['id'],$v['info']);
echo $v['id'];
echo '<br>';
}
}
}
}