当前位置:首页 > PHP

php实现翻译

2026-02-14 17:09:20PHP

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 并考虑缓存翻译结果以提高性能。

php实现翻译

标签: php
分享给朋友:

相关文章

php实现文件下载

php实现文件下载

PHP实现文件下载的方法 通过PHP实现文件下载功能,可以采用多种方式,以下是几种常见的实现方法: 使用header()函数强制下载 设置HTTP头信息,强制浏览器下载文件而非直接打开: $fi…

php实现验证码

php实现验证码

PHP实现验证码的方法 使用GD库生成验证码 GD库是PHP中处理图像的扩展,可用于生成验证码图片。 <?php session_start(); $width = 120; $height…

php实现图片上传

php实现图片上传

实现图片上传的基本步骤 创建HTML表单用于文件上传,表单需设置enctype="multipart/form-data"属性,确保文件数据正确传输。 <form action="upload…

php实现表单

php实现表单

PHP 表单基础实现 创建一个简单的 PHP 表单需要 HTML 表单结构和 PHP 处理脚本。以下是一个完整的示例: HTML 表单部分 (form.html) <form actio…

php长连接实现

php长连接实现

PHP 长连接实现方法 长连接(Keep-Alive)允许客户端与服务器在一次TCP连接中发送和接收多个HTTP请求/响应,减少重复建立连接的开销。以下是PHP中实现长连接的几种方式: 配置HT…

php实现登录

php实现登录

PHP 登录功能实现 数据库连接与用户表创建 创建一个数据库连接文件 db.php,用于管理数据库连接。MySQL 示例代码如下: <?php $host = 'localhost'; $db…