当前位置:首页 > PHP

php 实现翻译

2026-02-28 09:57:45PHP

PHP 实现翻译的方法

使用 Google Translate API

Google Translate API 是一种付费服务,提供高质量的翻译功能。需要注册 Google Cloud 账号并获取 API 密钥。

<?php
function translateText($text, $targetLanguage, $apiKey) {
    $url = "https://translation.googleapis.com/language/translate/v2?key=" . $apiKey;
    $data = array(
        'q' => $text,
        'target' => $targetLanguage
    );
    $options = array(
        'http' => array(
            '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);
    return $response['data']['translations'][0]['translatedText'];
}

$apiKey = 'YOUR_GOOGLE_API_KEY';
$text = 'Hello, world!';
$translatedText = translateText($text, 'es', $apiKey);
echo $translatedText;
?>

使用 Microsoft Translator API

Microsoft Translator API 是另一种付费翻译服务,提供多语言支持。

<?php
function microsoftTranslate($text, $targetLanguage, $apiKey) {
    $url = 'https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=' . $targetLanguage;
    $headers = array(
        'Ocp-Apim-Subscription-Key: ' . $apiKey,
        'Content-Type: application/json'
    );
    $data = array(array('Text' => $text));
    $options = array(
        'http' => array(
            '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);
    return $response[0]['translations'][0]['text'];
}

$apiKey = 'YOUR_MICROSOFT_API_KEY';
$text = 'Hello, world!';
$translatedText = microsoftTranslate($text, 'fr', $apiKey);
echo $translatedText;
?>

使用免费翻译 API (MyMemory)

MyMemory 是一个免费的翻译 API,适合小规模翻译需求。

<?php
function myMemoryTranslate($text, $targetLanguage) {
    $url = 'https://api.mymemory.translated.net/get?q=' . urlencode($text) . '&langpair=en|' . $targetLanguage;
    $result = file_get_contents($url);
    $response = json_decode($result, true);
    return $response['responseData']['translatedText'];
}

$text = 'Hello, world!';
$translatedText = myMemoryTranslate($text, 'de');
echo $translatedText;
?>

使用本地翻译库 (Stichoza/GoogleTranslate)

Stichoza/GoogleTranslate 是一个 PHP 库,模拟 Google 翻译的网页版请求,无需 API 密钥。

安装库:

composer require stichoza/google-translate-php

使用示例:

<?php
require 'vendor/autoload.php';
use Stichoza\GoogleTranslate\GoogleTranslate;

$tr = new GoogleTranslate('es');
echo $tr->translate('Hello, world!');
?>

使用数据库存储翻译

对于多语言网站,可以将翻译内容存储在数据库中,通过 PHP 动态加载。

数据库表结构示例:

CREATE TABLE translations (
    id INT AUTO_INCREMENT PRIMARY KEY,
    key VARCHAR(255) NOT NULL,
    language VARCHAR(10) NOT NULL,
    value TEXT NOT NULL
);

PHP 查询示例:

php 实现翻译

<?php
function getTranslation($key, $language) {
    $pdo = new PDO('mysql:host=localhost;dbname=your_db', 'username', 'password');
    $stmt = $pdo->prepare('SELECT value FROM translations WHERE key = ? AND language = ?');
    $stmt->execute([$key, $language]);
    $result = $stmt->fetch();
    return $result ? $result['value'] : $key;
}

echo getTranslation('welcome_message', 'fr');
?>

注意事项

  • 付费 API 如 Google 和 Microsoft 需要注册并获取 API 密钥。
  • 免费 API 可能有请求限制,不适合大规模使用。
  • 本地翻译库可能违反服务条款,需谨慎使用。
  • 数据库存储翻译适合静态内容,动态内容需结合 API 使用。

标签: php
分享给朋友:

相关文章

php队列的实现

php队列的实现

PHP队列的实现方式 PHP中实现队列功能可以通过多种方式,根据需求选择适合的方案: 使用数组实现基础队列 PHP数组本身支持队列操作,利用array_push和array_shift函数: $q…

php实现的分页

php实现的分页

PHP 实现分页的方法 基本分页逻辑 分页的核心在于计算总页数、当前页码以及数据偏移量。假设每页显示 10 条数据: $current_page = isset($_GET['page']) ? (…

php实现博客

php实现博客

使用PHP实现博客系统 数据库设计 创建数据库表存储博客文章和用户信息。常见的表包括posts(文章)和users(用户)。 CREATE TABLE users ( id INT AUTO…

php实现支付宝支付

php实现支付宝支付

支付宝支付集成步骤 准备工作 在开始集成支付宝支付前,确保已注册支付宝开放平台账号并完成企业实名认证。创建应用后获取APPID、应用私钥和支付宝公钥。 配置支付宝SDK 通过Composer安装支付…

php实现短信验证

php实现短信验证

PHP实现短信验证的步骤 选择合适的短信服务提供商 国内常见的短信服务提供商包括阿里云短信、腾讯云短信、云片等。注册账号并获取API密钥和签名模板是第一步。这些平台通常提供详细的开发文档和SDK。…

php实现注册登陆

php实现注册登陆

PHP 注册功能实现 创建数据库表结构(MySQL示例): CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, usern…