本文目录导读:

在 PHP 中处理文档翻译,主要有以下几种方式,取决于你的具体需求:
使用第三方翻译 API(推荐)
Google Translate API
<?php
function googleTranslate($text, $targetLang = 'zh-CN') {
$apiKey = 'YOUR_API_KEY';
$url = 'https://translation.googleapis.com/language/translate/v2';
$data = array(
'q' => $text,
'target' => $targetLang,
'key' => $apiKey
);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
$response = curl_exec($ch);
curl_close($ch);
$result = json_decode($response, true);
return $result['data']['translations'][0]['translatedText'];
}
// 使用示例
echo googleTranslate('Hello World');
DeepL API
<?php
function deeplTranslate($text, $targetLang = 'ZH') {
$apiKey = 'YOUR_API_KEY';
$url = 'https://api-free.deepl.com/v2/translate';
$data = array(
'auth_key' => $apiKey,
'text' => $text,
'target_lang' => $targetLang
);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
$response = curl_exec($ch);
curl_close($ch);
$result = json_decode($response, true);
return $result['translations'][0]['text'];
}
使用免费翻译服务
百度翻译 API
<?php
function baiduTranslate($query, $from = 'auto', $to = 'zh') {
$appid = 'YOUR_APP_ID';
$secretKey = 'YOUR_SECRET_KEY';
$salt = rand(10000, 99999);
$sign = md5($appid . $query . $salt . $secretKey);
$url = 'http://api.fanyi.baidu.com/api/trans/vip/translate';
$data = array(
'q' => $query,
'from' => $from,
'to' => $to,
'appid' => $appid,
'salt' => $salt,
'sign' => $sign
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url . '?' . http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$result = json_decode($response, true);
return isset($result['trans_result'][0]['dst']) ? $result['trans_result'][0]['dst'] : '';
}
批量翻译文档文件
翻译 DOCX 文件
<?php
require 'vendor/autoload.php';
use PhpOffice\PhpWord\IOFactory;
function translateDocument($inputFile, $outputFile) {
// 读取文档
$phpWord = IOFactory::load($inputFile);
foreach ($phpWord->getSections() as $section) {
foreach ($section->getElements() as $element) {
if ($element instanceof \PhpOffice\PhpWord\Element\TextRun) {
foreach ($element->getElements() as $textElement) {
if (method_exists($textElement, 'getText')) {
$text = $textElement->getText();
$translated = googleTranslate($text, 'zh-CN');
$textElement->setText($translated);
}
}
}
}
}
// 保存翻译后的文档
$writer = IOFactory::createWriter($phpWord, 'Word2007');
$writer->save($outputFile);
}
translateDocument('source.docx', 'translated.docx');
翻译 HTML/PDF 文件
翻译 HTML 文件
<?php
function translateHTML($htmlFile, $targetLang = 'zh-CN') {
$html = file_get_contents($htmlFile);
// 简单示例:翻译文本节点
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($html);
libxml_clear_errors();
$xpath = new DOMXPath($dom);
$textNodes = $xpath->query('//text()[normalize-space()]');
foreach ($textNodes as $node) {
$text = trim($node->nodeValue);
if (strlen($text) > 0) {
$translated = googleTranslate($text, $targetLang);
$node->nodeValue = $translated;
}
}
return $dom->saveHTML();
}
使用 Composer 包
composer require stichoza/google-translate-php
<?php
use Stichoza\GoogleTranslate\GoogleTranslate;
$tr = new GoogleTranslate('zh-CN');
$translated = $tr->translate('Hello World');
echo $translated;
代码示例:完整的文档翻译类
<?php
class DocumentTranslator {
private $apiKey;
private $provider;
public function __construct($apiKey, $provider = 'google') {
$this->apiKey = $apiKey;
$this->provider = $provider;
}
public function translate($text, $targetLang = 'zh-CN') {
switch ($this->provider) {
case 'google':
return $this->translateWithGoogle($text, $targetLang);
case 'deepl':
return $this->translateWithDeepL($text, $targetLang);
case 'baidu':
return $this->translateWithBaidu($text, $targetLang);
default:
throw new Exception('不支持的翻译服务');
}
}
private function translateWithGoogle($text, $targetLang) {
// Google API 调用代码
}
private function translateWithDeepL($text, $targetLang) {
// DeepL API 调用代码
}
private function translateWithBaidu($text, $targetLang) {
// 百度 API 调用代码
}
public function translateFile($inputPath, $outputPath, $fileType) {
// 根据文件类型调用不同的翻译方法
}
}
// 使用示例
$translator = new DocumentTranslator('YOUR_API_KEY');
echo $translator->translate('Hello, how are you?');
注意事项:
- API 限制:免费 API 通常有每日请求限制
- 文本长度:部分 API 有单次翻译字符限制
- 网络请求:确保安装了 cURL 扩展
- 错误处理:添加适当的错误处理机制
- 编码问题:确保正确处理 UTF-8 编码
选择哪种方法取决于你的具体需求:翻译单个文本、批量翻译文档、还是翻译网页内容。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播