php 实现翻译
使用 Google Translate API
PHP 可以通过调用 Google Translate API 实现翻译功能。需要注册 Google Cloud 账号并获取 API 密钥。
$apiKey = 'YOUR_GOOGLE_API_KEY';
$text = 'Hello, world!';
$targetLanguage = 'zh';
$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);
$response = file_get_contents($url, false, $context);
$result = json_decode($response, true);
echo $result['data']['translations'][0]['translatedText'];
使用 Microsoft Translator API
Microsoft Azure 也提供翻译服务,需要注册 Azure 账号并获取 API 密钥。
$apiKey = 'YOUR_AZURE_API_KEY';
$text = 'Hello, world!';
$targetLanguage = 'zh-Hans';
$url = "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=$targetLanguage";
$headers = [
'Ocp-Apim-Subscription-Key: ' . $apiKey,
'Content-Type: application/json'
];
$body = json_encode([['Text' => $text]]);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$result = json_decode($response, true);
echo $result[0]['translations'][0]['text'];
使用本地翻译库
对于不需要实时联网的场景,可以使用本地翻译库如 PHP-Google-Translate-Free。
require 'vendor/autoload.php';
use Statickidz\GoogleTranslate;
$source = 'en';
$target = 'zh';
$text = 'Hello, world!';
$trans = new GoogleTranslate();
$result = $trans->translate($source, $target, $text);
echo $result;
使用数据库存储翻译
对于多语言网站,可以在数据库中存储翻译内容。
$pdo = new PDO('mysql:host=localhost;dbname=translations', 'username', 'password');
$text = 'Welcome';
$language = 'fr';
$stmt = $pdo->prepare("SELECT translation FROM translations WHERE original = ? AND language = ?");
$stmt->execute([$text, $language]);
$result = $stmt->fetch();
echo $result['translation'];
使用 gettext 扩展
PHP 内置的 gettext 扩展适合本地化应用程序。

putenv('LC_ALL=fr_FR');
setlocale(LC_ALL, 'fr_FR');
bindtextdomain('messages', './locale');
textdomain('messages');
echo _("Hello, world!");
每种方法适用于不同场景,API 方式适合需要高质量实时翻译,本地库适合离线环境,数据库方式适合网站多语言支持,gettext 适合应用程序本地化。






