💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
执行调用方法: ~~~ use support\lib\Translator; public function index() { $fieldVal = '想要进行顺利的话,吉日是非常重要的。而且这也是一个订婚纪念日,很适合被记住,快来看看2021年农历九月二十是黄历订婚吉日吗。'; $fieldVal = '<div>订婚一定要选择合适的日子,<span style="font-size:18px;">这个日子</span>需要经过精挑细选才可以,并且对将来的婚姻很有好处,</div><div>想要进行顺利的话,吉日是非常重要的。而且这也是一个订婚纪念日,很适合被记住,快来看看2021年农历九月二十是黄历订婚吉日吗。</div>'; $params = [ 'from' => 'zh', 'to' => 'en' ]; $res = Translator::translate($fieldVal, $params); return ($res); } ~~~ 类库代码: ~~~ <?php /*翻译器*/ namespace support\lib; class Translator { private static function tranConfig() { $defaultConfig = [ 'interval' => '100', //调用间隔(毫秒,1000毫秒=1秒) 'wait' => '2', //失败等待(秒) 'retry' => '1', //失败重试次数 'pass_html' => true, //是否开启html过滤 'defaultApi' => 'baidu', //默认接口 'spareApi' => 'youdao', //备用接口 'baidu' => [ 'appid' => '', 'key' => '' ], 'youdao' => [ 'app_id' => '', 'key' => '' ] ]; $tranConfig = config('translate_config'); if (empty($tranConfig)) { $tranConfig = $defaultConfig; } return $tranConfig; } public static $all_langs = array( 'zh' => '中文', 'en' => '英语', 'fra' => '法语', 'jp' => '日语', 'kor' => '韩语', 'de' => '德语', 'ru' => '俄语', 'spa' => '西班牙语', 'pt' => '葡萄牙语', 'it' => '意大利语', 'ara' => '阿拉伯语', 'th' => '泰语', 'el' => '希腊语', 'nl' => '荷兰语', 'pl' => '波兰语', 'bul' => '保加利亚语', 'est' => '爱沙尼亚语', 'dan' => '丹麦语', 'fin' => '芬兰语', 'cs' => '捷克语', 'rom' => '罗马尼亚语', 'slo' => '斯洛文尼亚语', 'swe' => '瑞典语', 'hu' => '匈牙利语', 'tr' => '土耳其语', 'id' => '印尼语', 'ms' => '马来西亚语', 'vie' => '越南语', 'yue' => '粤语', 'wyw' => '文言文', 'cht' => '繁体中文' ); public static $allow_langs = array( 'baidu' => array( 'zh' => 'zh', 'en' => 'en', 'fra' => 'fra', 'jp' => 'jp', 'kor' => 'kor', 'de' => 'de', 'ru' => 'ru', 'spa' => 'spa', 'pt' => 'pt', 'it' => 'it', 'ara' => 'ara', 'th' => 'th', 'el' => 'el', 'nl' => 'nl', 'pl' => 'pl', 'bul' => 'bul', 'est' => 'est', 'dan' => 'dan', 'fin' => 'fin', 'cs' => 'cs', 'rom' => 'rom', 'slo' => 'slo', 'swe' => 'swe', 'hu' => 'hu', 'vie' => 'vie', 'yue' => 'yue', 'wyw' => 'wyw', 'cht' => 'cht' ), 'youdao' => array( 'zh' => 'zh-CHS', 'en' => 'en', 'jp' => 'ja', 'kor' => 'ko', 'fra' => 'fr', 'spa' => 'es', 'pt' => 'pt', 'it' => 'it', 'ru' => 'ru', 'vie' => 'vi', 'de' => 'de', 'ara' => 'ar', 'id' => 'id', 'it' => 'it' ), 'qq' => array( 'zh' => 'zh', 'en' => 'en', 'jp' => 'jp', 'kor' => 'kr', 'de' => 'de', 'fra' => 'fr', 'spa' => 'es', 'it' => 'it', 'tr' => 'tr', 'ru' => 'ru', 'pt' => 'pt', 'vie' => 'vi', 'id' => 'id', 'ms' => 'ms', 'th' => 'th', 'cht' => 'zh-TW' ) ); /*翻译入口*/ public static function translate($fieldVal, $params) { $transConf = self::tranConfig(); $pass_html = $transConf['pass_html']; static $regEmpty = '/^([\s\r\n]|\&nbsp\;)*$/'; //开启html过滤 if ($pass_html == true) { $htmlMd5List = []; $txtMd5List = []; static $tagRegs = array( '/<\![\s\S]*?>/', '/<(script|style)[^\r\n]*?>[\s\S]*?<\/\1>/i', '/<[\/]*\w+\b[^\r\n]*?>/' ); foreach ($tagRegs as $tagReg) { $fieldVal = preg_replace_callback($tagReg, function ($mhtml) use (&$htmlMd5List) { $key = '{'.md5($mhtml[0]).'}'; $htmlMd5List[$key] = $mhtml[0]; return $key; }, $fieldVal); } if (empty($htmlMd5List)) { //不包含html代码 if ( ! empty($fieldVal) && ! preg_match($regEmpty, $fieldVal)) { $fieldVal = self::execute_translate($fieldVal, $params['from'], $params['to']); } } else { //包含html代码 $fieldVal = preg_replace_callback('/([\s\S]*?)(\{[a-zA-Z0-9]{32}\})/i', function ($mtxt) use (&$txtMd5List) { $key = '['.md5($mtxt[1]).']'; $txtMd5List[$key] = $mtxt[1]; return $key.$mtxt[2]; }, $fieldVal); foreach ($txtMd5List as $k => $v) { if ( ! empty($v) && ! preg_match($regEmpty, $v)) { $txtMd5List[$k] = self::execute_translate($v, $params['from'], $params['to']); } } if ( ! empty($txtMd5List)) { $fieldVal = str_replace(array_keys($txtMd5List), $txtMd5List, $fieldVal); } if ( ! empty($htmlMd5List)) { $fieldVal = str_replace(array_keys($htmlMd5List), $htmlMd5List, $fieldVal); } } } else { if ( ! empty($fieldVal) && ! preg_match($regEmpty, $fieldVal)) { $fieldVal = self:: execute_translate($fieldVal, $params['from'], $params['to']); } } return $fieldVal; } public static function translate_f($q, $from, $to, $returnState = false) { $transConf = self::tranConfig(); if (empty($from) || empty($to)) { return $q; } $apiType = strtolower($transConf['defaultApi']); $spareType = strtolower($transConf['spareApi']); if (empty($apiType)) { return $q; } $allowLangs = self::$allow_langs[$apiType]; if (empty($allowLangs)) { return $q; } $from = $allowLangs[$from]; $to = $allowLangs[$to]; if (empty($from) || empty($to)) { return $q; } if ($from == $to) { return $q; } //默认线路执行失败后,执行备用线路 $return = self::sendTranslate($q, $apiType, $from, $to); if ( ! empty($return) && $return['success'] === false) { $return = self::sendTranslate($q, $spareType, $from, $to); } if ($returnState) { return $return; } else { return empty($return['success']) ? $q : $return['data']; } } public static function sendTranslate($q, $apiType, $from, $to) { switch ($apiType) { case "baidu"; $return = self::api_baidu($q, $from, $to); break; case "youdao"; $return = self::api_youdao($q, $from, $to); break; case "qq"; $return = self::api_qq($q, $from, $to); break; } return $return; } /*百度翻译接口*/ public static function api_baidu($q, $from, $to) { $apiConf = self::tranConfig()['baidu']; $salt = time(); $sign = $apiConf['appid'].$q.$salt.$apiConf['key']; $sign = md5($sign); $url = "https://api.fanyi.baidu.com/api/trans/vip/translate"; $postData = [ 'from' => $from, 'to' => $to, 'appid' => $apiConf['appid'], 'salt' => $salt, 'sign' => $sign, 'q' => $q ]; $data = curl_post($url, $postData); $data = json_decode($data, true); $return = array('success' => false); if ( ! empty($data['error_code'])) { $return['error'] = 'error:'.$data['error_code'].'-'.$data['error_msg']; } else { $transData = ''; foreach ($data['trans_result'] as $trans) { $transData .= $trans['dst']."\r\n"; } if ($transData) { $return['success'] = true; $return['data'] = $transData; } } return $return; } /*有道翻译接口*/ public static function api_youdao($q, $from, $to) { $apiConf = self::tranConfig()['youdao']; $salt = time(); $sign = $apiConf['app_id'].$q.$salt.$apiConf['key']; $sign = md5($sign); $url = "https://openapi.youdao.com/api"; $postData = [ 'from' => $from, 'to' => $to, 'appKey' => $apiConf['app_id'], 'salt' => $salt, 'sign' => $sign, 'q' => $q ]; $data = curl_post($url, $postData); $data = json_decode($data, true); $return = array('success' => false); if ( ! empty($data['errorCode'])) { $return['error'] = 'error:'.$data['errorCode']; } else { $transData = ''; foreach ($data['translation'] as $trans) { $transData .= $trans."\r\n"; } if ($transData) { $return['success'] = true; $return['data'] = $transData; } } return $return; } /*腾讯翻译接口*/ public static function api_qq($q, $from, $to) { $apiConf = self::tranConfig()['qq']; $SecretId = $apiConf['secretid']; $SecretKey = $apiConf['secretkey']; $param = array(); $param["Nonce"] = rand(); $param["Timestamp"] = time(); $param["Region"] = "ap-shanghai"; $param["SecretId"] = $SecretId; $param["Action"] = "TextTranslate"; $param["Version"] = "2018-03-21"; $param["SourceText"] = $q; $param["Source"] = $from; $param["Target"] = $to; $param['ProjectId'] = '0'; ksort($param); $signStr = "GETtmt.ap-shanghai.tencentcloudapi.com/?"; foreach ($param as $key => $value) { $signStr = $signStr.$key."=".$value."&"; } $signStr = substr($signStr, 0, -1); $param['Signature'] = base64_encode(hash_hmac("sha1", $signStr, $SecretKey, true)); $return = array('success' => false); ksort($param); $url = ''; foreach ($param as $key => $value) { $url = $url.$key."=".urlencode($value)."&"; } $url = trim($url, '&'); $data = get_html('https://tmt.'.$param["Region"].'.tencentcloudapi.com/?'.$url, null, null, 'utf-8'); $data = json_decode($data, true); if ( ! empty($data['Response']['TargetText'])) { $return['success'] = true; $return['data'] = $data['Response']['TargetText']; } return $return; } public static function get_api_langs($api) { $allowLangs = self::$allow_langs[$api]; if ( ! empty($allowLangs) && is_array($allowLangs)) { foreach ($allowLangs as $k => $v) { if (empty(self::$all_langs[$k])) { unset($allowLangs[$k]); } else { $allowLangs[$k] = self::$all_langs[$k]; } } } return is_array($allowLangs) ? $allowLangs : null; } /*数据处理:翻译*/ private static function execute_translate($q, $from, $to) { static $retryCur = 0; $transConf = self::tranConfig(); $transConf['interval'] = intval($transConf['interval']); $transConf['wait'] = intval($transConf['wait']); $transConf['retry'] = intval($transConf['retry']); $retryMax = $transConf['retry']; $return = Translator::translate_f($q, $from, $to, true); if (is_array($return)) { if ($transConf['interval'] > 0) { usleep($transConf['interval'] * 1000); } if ( ! empty($return['success'])) { $retryCur = 0; $return = $return['data']; } else { if ($retryMax <= 0 || ($retryCur <= 0)) { return error_json('数据处理»翻译失败'); } if ($transConf['wait'] > 0) { sleep($transConf['wait']); } if ($retryMax > 0) { if ($retryCur < $retryMax) { $retryCur++; return self::execute_translate($q, $from, $to); } else { $retryCur = 0; return error_json('数据处理»翻译:已重试'.$retryMax.'次,翻译无效'); } } } } return $return; } } /** * 返回success_json数组 * @param $arr * @return string */ function success_json($msg = 'ok', $data = [], $count = 0, $url = '', $wait = 3) { $result = ['code' => 200, 'msg' => $msg, 'data' => $data]; return json($result); } /** * 返回success_json数组 * @param $arr * @return string */ function error_json($msg = 'error', $data = [], $url = '', $wait = 3) { $result = [ 'code' => 0, 'msg' => $msg, 'data' => $data, ]; return json($result); } ?> ~~~