
ショコラ
PHP Google_Service_CloudNaturalLanguageを使うには?
Google Cloud プラットフォーム を使う。
ここも初めはかなり謎の部分ですので、インターネットで調べるしかないです。
おおざっぱに下の手順が必要です。
①プロジェクトを作成する。
②Marketplaceから「Cloud Natural Language API」を「有効化」する。
③認証情報を作成する。(サービスアカウント作る)
④サービスアカウントの秘密鍵(JSON)の作成する。
その秘密鍵(JSONファイル)で認証して使います。
※サービスアカウント使わなくてもAPIキーでいけましたが、サービスアカウントを使う流れでいきます。

もっさん先輩
Laravel のコマンドで Google Cloud Natural Language API を使ってみます。
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class GoogleCloudNaturalLanguage extends Command
{
protected $signature = 'lang';
protected $description = 'Google Cloud Natural Language API のサンプルプログラム';
public function handle()
{
// サービスアカウントのJSON
$google_credentials_json =<<< 'GOOGLE_CREDENTIALS_JSON'
{
"type": "service_account",
:
"universe_domain": "googleapis.com"
}
GOOGLE_CREDENTIALS_JSON;
$client = new \Google_Client();
$client->setScopes( \Google_Service_CloudNaturalLanguage::CLOUD_LANGUAGE );
// 認証
$auth = tempnam(sys_get_temp_dir(),'auth-');
file_put_contents($auth,$google_credentials_json);
$client->setAuthConfig($auth);
unlink($auth);
// Google_Service_CloudNaturalLanguageオブジェクトを作成
$service = new \Google_Service_CloudNaturalLanguage($client);
$text =<<< INPUT
:
INPUT;
// テキストの分析リクエストを作成
$document = new \Google_Service_CloudNaturalLanguage_Document();
$document->setContent($text);
$document->setType('PLAIN_TEXT');
// リクエストの作成
$request = new \Google_Service_CloudNaturalLanguage_AnalyzeEntitiesRequest();
$request->setDocument($document);
// エンティティ分析を実行
$response = $service->documents->analyzeEntities($request);
// エンティティの結果を表示
foreach ($response->getEntities() as $entity) {
echo "Entity: " . $entity['name'] . "\n";
echo "Type: " . $entity['type'] . "\n";
echo "Salience: " . $entity['salience'] . "\n\n";
}
}
}
以上