首页 > PHP
ThinkPHP对接阿里云翻译API接口
来源:TP课堂 时间:2023-05-03 点击:553

五一假期抠了两天图,把我累的,真是劳动人民了,真正感觉到程序是改变世界的,可以实现批量干活。

展现技术的时刻到了:批量翻译。工作量:普通文章的长度,数量大约1500篇。

先是看了百度翻译,看了文档,感觉怪怪的,就放弃了,然后就是阿里云了,先composer一把:

composer require alibabacloud/sdk

然后就是代码了:

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
public function t(){
        // 创建一个全局客户端
        AlibabaCloud::accessKeyClient('LTAI5t7oAWLQco', '6ZNBWAHIHpu')
        ->regionId('cn-hangzhou')
        ->asGlobalClient();
        $archivesData=Db::name('spanish_product')->field('id,seo_description')->select()->toArray();
        foreach($archivesData as $k=>$v){
            try {
                $result = AlibabaCloud::alimt()
                            ->v20181012()                //通用版本
                            ->translateGeneral()
                            ->method('POST')            //设置请求POST
                            ->withSourceLanguage('en')    //源语言
                            ->withSourceText($v['seo_description'])    //原文
                            ->withFormatType('html')    //翻译文本的格式
                            ->withTargetLanguage('es')    //目标语言
                            ->request();
       
                $Arr=$result->toArray();
                //halt($Arr['Data']['Translated']);
                Db::name('spanish_product')->where('id',$v['id'])->update(['seo_description'=>$Arr['Data']['Translated']]);
                echo $v['id'];
                echo "<br>";
                } catch (ServerException $e) {
                \print_r($e->getErrorMessage());
                \print_r($e->getRequestId());
                } catch (ClientException $e) {
                \print_r($e->getErrorMessage());
            }

        }

       
    }

注意量太大的时候容易断掉,直接整死了,我是每400条文章一次,你的文章长度比较长可以在200条-300条处理一次。

效率太高,速度太快了!

一定要购买翻译包,我就没买,结果产生了近800元的翻译费用,别说了我去哭了……