Google翻译 google/cloud-translate 使用方法
流程
准备工作
- 注册google账号
- 创建结算账号
- 创建项目 https://console.cloud.google.com/projectselector2/iam-admin/serviceaccounts?hl=zh_CN
- 创建服务账号
- 创建服务账号的秘钥,下载到本地
- 设置有秘钥的服务账号资源权限
- composer require google/cloud-translate
代码
require 'vendor/autoload.php';
use Google\Cloud\Translate\V3\TranslationServiceClient;
$translationClient = new TranslationServiceClient();
$content = ['one', 'two', 'three']; //数组形式可传多个
$targetLanguage = 'es'; 目标语言
$response = $translationClient->translateText(
$content,
$targetLanguage,
TranslationServiceClient::locationName('[PROJECT_ID]', 'global') // project_id是你的项目id,global是你秘钥的本地地址
);
foreach ($response->getTranslations() as $key => $translation) {
$separator = $key === 2
? '!'
: ', ';
echo $translation->getTranslatedText() . $separator;
}