以下是一步步教你使用PHP对接百度智能翻译接口的方法:
首先,你需要在百度开发者平台上创建一个应用,并获取到你的API Key和Secret Key。这些信息将用于访问百度智能翻译接口。
在你的PHP项目中,创建一个名为baidu_translate.php
的文件,并在文件中添加以下代码:
<?php
function translate($query, $from, $to) {
$url = 'https://fanyi-api.baidu.com/api/trans/vip/translate';
$appKey = 'YOUR_APP_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$salt = rand(10000, 99999);
$sign = md5($appKey . $query . $salt . $secretKey);
$params = array(
'q' => $query,
'from' => $from,
'to' => $to,
'appid' => $appKey,
'salt' => $salt,
'sign' => $sign
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$result = json_decode($response, true);
if (isset($result['error_code'])) {
return '翻译失败: ' . $result['error_msg'];
} else {
return $result['trans_result'][0]['dst'];
}
}
请确保将YOUR_APP_KEY
和YOUR_SECRET_KEY
替换为你在百度开发者平台上创建应用时获取到的API Key和Secret Key。
translate
函数进行翻译:<?php
require_once('baidu_translate.php');
$query = 'Hello world';
$from = 'en';
$to = 'zh';
$result = translate($query, $from, $to);
echo $result;
请将$query
设置为你要翻译的文本,$from
设置为源语言,$to
设置为目标语言。
这样,你就可以使用PHP对接百度智能翻译接口进行翻译了。记得在使用之前,确保你的PHP项目已经安装了cURL扩展库。
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站