<?php
require_once 'vendor/autoload.php';
use GoogleCloudTranslateV2TranslateClient;
// Replace with your own project ID and API key
$projectId = 'your-project-id';
$apiKey = 'your-api-key';
// Create a new client
$client = new TranslateClient([
'projectId' => $projectId,
'key' => $apiKey
]);
// Define the text to be translated and the target language
$text = 'Hello, world!';
$targetLanguage = 'fr';
// Translate the text
$result = $client->translate($text, [
'target' => $targetLanguage
]);
// Print the translated text
echo $result['text'];
?>
在这个示例中,我们首先引入Google Cloud PHP库。然后,我们创建了一个新的TranslateClient实例并传递了我们的项目ID和API密钥。接下来,我们定义了要翻译的文本和目标语言。最后,我们调用translate()方法来进行翻译,并打印出翻译结果。
需要注意的是,您需要替换示例中的$projectId和$apiKey变量为您自己的项目ID和API密钥。