# PHP對Google Translate谷歌翻譯API的使用教程
## 前言
Google Translate作為全球領先的機器翻譯服務,其API為開發者提供了強大的多語言互譯能力。本教程將詳細介紹如何通過PHP調用Google Cloud Translation API,包含從項目創建到代碼實現的完整流程。
---
## 一、準備工作
### 1.1 創建Google Cloud項目
1. 訪問[Google Cloud Console](https://console.cloud.google.com/)
2. 點擊"創建項目"并填寫項目名稱
3. 記下生成的**項目ID**(后續需要用到)
### 1.2 啟用Translation API
1. 在導航菜單選擇"API和服務" > "庫"
2. 搜索"Cloud Translation API"
3. 點擊"啟用"按鈕
### 1.3 創建服務賬號密鑰
1. 進入"API和服務" > "憑據"
2. 點擊"創建憑據"選擇"服務賬號"
3. 生成JSON格式密鑰文件并妥善保存
```json
// 示例密鑰文件結構
{
"type": "service_account",
"project_id": "your-project-id",
"private_key_id": "xxxxxxxx",
"private_key": "-----BEGIN PRIVATE KEY-----\nxxxxxx\n-----END PRIVATE KEY-----\n",
"client_email": "xxx@xxx.iam.gserviceaccount.com",
"client_id": "1234567890"
}
composer require google/cloud-translate
將密鑰文件路徑添加到.env:
GOOGLE_APPLICATION_CREDENTIALS="/path/to/your/service-account.json"
require 'vendor/autoload.php';
use Google\Cloud\Translate\V2\TranslateClient;
$translate = new TranslateClient([
'keyFilePath' => getenv('GOOGLE_APPLICATION_CREDENTIALS')
]);
// 單條文本翻譯
$result = $translate->translate('Hello world', [
'target' => 'zh-CN'
]);
echo $result['text']; // 輸出: 你好世界
$texts = ['apple', 'banana', 'orange'];
$results = $translate->translateBatch($texts, [
'target' => 'fr'
]);
foreach ($results as $result) {
echo $result['text'] . "\n";
}
// 輸出: pomme, banane, orange
$detection = $translate->detectLanguage('こんにちは');
echo "檢測到語言: {$detection['language']}"; // 輸出: ja
$languages = $translate->localizedLanguages([
'target' => 'zh-CN' // 獲取中文顯示的語言名稱
]);
foreach ($languages as $language) {
printf("%s: %s\n", $language['code'], $language['name']);
}
$advancedTranslate = new TranslateClient([
'keyFilePath' => 'credentials.json',
'projectId' => 'your-project-id'
]);
$glossaryConfig = [
'glossary' => 'projects/your-project-id/locations/us-central1/glossaries/tech-glossary'
];
$result = $advancedTranslate->translate('Kubernetes cluster', [
'target' => 'zh-CN',
'glossaryConfig' => $glossaryConfig
]);
try {
$result = $translate->translate($text, ['target' => $targetLang]);
} catch (\Google\Cloud\Core\Exception\ServiceException $e) {
echo "API錯誤: " . $e->getMessage();
// 可添加重試邏輯
}
$translate = new TranslateClient([
'keyFilePath' => 'credentials.json',
'httpOptions' => [
'debug' => fopen('php://stderr', 'w')
]
]);
// 緩存示例
function cachedTranslate($text, $targetLang) {
$cacheKey = md5($text.$targetLang);
if ($cached = apc_fetch($cacheKey)) {
return $cached;
}
$result = $translate->translate($text, ['target' => $targetLang]);
apc_store($cacheKey, $result, 3600);
return $result;
}
<?php
require 'vendor/autoload.php';
class GoogleTranslator {
private $client;
public function __construct($keyPath) {
$this->client = new \Google\Cloud\Translate\V2\TranslateClient([
'keyFilePath' => $keyPath
]);
}
public function translateText($text, $target = 'zh-CN', $source = null) {
$options = ['target' => $target];
if ($source) $options['source'] = $source;
try {
return $this->client->translate($text, $options);
} catch (Exception $e) {
error_log($e->getMessage());
return false;
}
}
public function detectLanguage($text) {
return $this->client->detectLanguage($text);
}
}
// 使用示例
$translator = new GoogleTranslator('path/to/credentials.json');
$result = $translator->translateText('Hello world');
print_r($result);
通過本教程,您應該已經掌握了: 1. Google Translation API的基本配置 2. PHP客戶端的安裝與使用 3. 基礎翻譯與高級功能的實現 4. 生產環境中的優化策略
建議進一步閱讀: - 官方PHP客戶端文檔 - API版本差異說明 “`
(注:實際字符數約1680字,可根據需要調整部分章節的詳細程度)
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。