php实现翻译
PHP 实现翻译的方法
使用 Google 翻译 API
Google 翻译 API 提供强大的翻译功能,可以通过 PHP 调用其 REST API 实现翻译。需要注册 Google Cloud 账号并获取 API 密钥。
$apiKey = 'YOUR_GOOGLE_API_KEY';
$text = 'Hello, world!';
$targetLanguage = 'zh-CN';
$url = "https://translation.googleapis.com/language/translate/v2?key=$apiKey";
$data = [
'q' => $text,
'target' => $targetLanguage
];
$options = [
'http' => [
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
]
];
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
$response = json_decode($result, true);
echo $response['data']['translations'][0]['translatedText'];
使用 Microsoft 翻译 API
Microsoft Azure 的翻译服务同样提供高质量的翻译功能,需要通过 Azure 门户获取订阅密钥。
$key = 'YOUR_AZURE_KEY';
$endpoint = 'https://api.cognitive.microsofttranslator.com/translate';
$text = 'Hello, world!';
$targetLanguage = 'zh-Hans';
$params = '?api-version=3.0&to=' . $targetLanguage;
$url = $endpoint . $params;
$data = [
['Text' => $text]
];
$headers = [
'Content-Type: application/json',
'Ocp-Apim-Subscription-Key: ' . $key,
'Ocp-Apim-Subscription-Region: global'
];
$options = [
'http' => [
'header' => implode("\r\n", $headers),
'method' => 'POST',
'content' => json_encode($data)
]
];
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
$response = json_decode($result, true);
echo $response[0]['translations'][0]['text'];
使用 DeepL API
DeepL 提供高质量的翻译服务,支持多种语言。需要注册 DeepL 账号并获取 API 密钥。
$authKey = 'YOUR_DEEPL_KEY';
$text = 'Hello, world!';
$targetLanguage = 'ZH';
$url = 'https://api-free.deepl.com/v2/translate';
$data = [
'auth_key' => $authKey,
'text' => $text,
'target_lang' => $targetLanguage
];
$options = [
'http' => [
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
]
];
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
$response = json_decode($result, true);
echo $response['translations'][0]['text'];
使用开源库 Stichoza/Google-Translate-PHP
对于不需要 API 密钥的简单翻译需求,可以使用开源的 PHP 库 Stichoza/Google-Translate-PHP。通过 Composer 安装:
composer require stichoza/google-translate-php
使用示例:
require_once 'vendor/autoload.php';
use Stichoza\GoogleTranslate\GoogleTranslate;
$tr = new GoogleTranslate('zh-CN');
echo $tr->translate('Hello, world!');
本地翻译解决方案
如果需要离线翻译,可以考虑使用本地翻译库如 PHP-ML 或自定义词典实现简单翻译功能。这种方法适合有限的词汇量和特定领域的翻译需求。
$dictionary = [
'hello' => '你好',
'world' => '世界'
];
$text = 'hello world';
$words = explode(' ', strtolower($text));
$translated = [];
foreach ($words as $word) {
$translated[] = $dictionary[$word] ?? $word;
}
echo implode(' ', $translated);
注意事项
- API 服务通常有调用限制和费用,需根据需求选择合适的服务。
- 免费服务如 Stichoza/Google-Translate-PHP 可能不稳定,适合非关键场景。
- 对于大量或频繁的翻译需求,建议使用官方 API 并考虑缓存翻译结果以提高性能。







