[php] Google Cloud Translation APIを導入
Google翻訳APIである「Google Cloud Translation API」をphpでプログラムするには以下の通り
composerでパッケージを追加
phpファイルを置く場所に移動して下記コマンドを実行してインストールする
composer require google/cloud-translate
Google Cloud Platformの「プロジェクトID」と「Google Cloud Translation API」の「APIキー」をGoogle APIの管理画面「Google API Console」で取得
https://console.cloud.google.com/apis/library?hl=ja
phpファイルの実装
<?php require_once '/vendor/autoload.php'; use Google\Cloud\Translate\TranslateClient; //Google APIの「プロジェクトID」 $projectId = 'プロジェクトID'; //「Google Cloud Translation API」の「APIキー」 $apiKey = 'APIキー'; //「TranslateClient」クラスを呼び出し $translate = new TranslateClient([ 'projectId' => $projectId, 'key' => $apiKey, ]); //翻訳したい言語を指定。今回は「日本語→英語」なので「en」 $lang = "en"; //翻訳開始 $result = $translate->translate("今日も、いい天気ですね。", [ 'target' => $lang, ]); var_dump($result);
APIからの戻り値
array(4) { ["source"]=> string(2) "ja" ["input"]=> string(36) "今日も、いい天気ですね。" ["text"]=> string(36) "It is nice weather today, is not it?" ["model"]=> NULL }