2024年09月06日 建站教程
1、引入PHP百度翻译API类,新建BaiduTranslate.php文件
<?php class BaiduTranslate { private $appId = 'your_app_id'; // 替换为你的App ID private $appKey = 'your_app_key'; // 替换为你的App Key public function translate($query, $from, $to) { $salt = rand(10000, 99999); $sign = md5($this->appId . $query . $salt . $this->appKey); $url = 'https://fanyi-api.baidu.com/api/trans/vip/translate?q=' . urlencode($query) . '&from=' . $from . '&to=' . $to . '&appid=' . $this->appId . '&salt=' . $salt . '&sign=' . $sign; $result = file_get_contents($url); $result = json_decode($result, true); if (isset($result['error_code'])) { throw new Exception($result['error_msg']); } return $result['trans_result'][0]['dst']; } } ?>
2、百度翻译API进行意大利语到日语的翻译
<?php require_once 'BaiduTranslate.php'; $translator = new BaiduTranslate(); $query = 'Ciao, come stai?'; $from = 'it'; $to = 'jp'; try { $translation = $translator->translate($query, $from, $to); echo $translation; } catch (Exception $e) { echo '翻译失败:' . $e->getMessage(); } ?>
本文链接:http://so.lmcjl.com/news/12379/