File: /www/wwwroot/www.baofufacai.com////f.php
<?php
/**
* 使用 Google 翻译 API 封装的 PHP 接口
*/
class GoogleTranslate {
private $api_key; // 申请的 API Key
public function __construct($api_key) {
$this->api_key = $api_key;
}
// 翻译函数
public function translate($text, $source_lang, $target_lang) {
$url = 'https://translation.googleapis.com/language/translate/v2?key=' . $this->api_key;
// 构造 API 请求参数
$params = array(
'q' => $text,
'source' => $source_lang,
'target' => $target_lang,
'format' => 'text'
);
// 发送 API 请求并处理返回结果
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($curl);
curl_close($curl);
// 解析返回的结果
$data = json_decode($result, true);
if(isset($data['data']) && isset($data['data']['translations']) && count($data['data']['translations']) > 0) {
return $data['data']['translations'][0]['translatedText'];
}
return null;
}
}
// 使用示例:
$api_key = 'AIzaSyApV2SnkzCF9mrXDZqyM8mbvZpU-q0kS84'; // 替换为你自己的 API Key
$translate = new GoogleTranslate($api_key);
$text = "How to set the translation!"; // 待翻译的文本
$source_lang = 'en'; // 原始语言
$target_lang = 'zh-CN'; // 目标语言
$result = $translate->translate($text, $source_lang, $target_lang);
echo "翻译结果:{$result}";
?>