LOADING

Google翻译 google/cloud-translate 使用方法

流程
准备工作

  1. 注册google账号
  2. 创建结算账号
  3. 创建项目 https://console.cloud.google.com/projectselector2/iam-admin/serviceaccounts?hl=zh_CN
  4. 创建服务账号
  5. 创建服务账号的秘钥,下载到本地
  6. 设置有秘钥的服务账号资源权限
  7. 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;
}

标签: PHP

添加新评论