使用方法:
此次是中文转英文
$translate= (new Googletranslation())->googleTranslate('zh-CN','en',$list['name']);
/**
* 谷歌翻译
* @param $source
* @param $target
* @param $text
* @return string
* @throws Exception
*/
public function googleTranslate($source, $target, $text)
{
// Request translation
$response = $this->requestTranslation($source, $target, $text);
// Clean translation
$translation = $this->getSentencesFromJSON($response);
return $translation;
}
public function requestTranslation($source, $target, $text)
{
// if (strlen($text) >= 5000) return $text;
// Google translate URL
$url = "https://translate.googleapis.com/translate_a/single?client=gtx&dt=t";
// dd($url);
$fields = array(
'sl' => urlencode($source),
'tl' => urlencode($target),
'q' => urlencode($text)
);
// URL-ify the data for the POST
$fields_string = "";
foreach ($fields as $key => $value) {
$fields_string .= '&' . $key . '=' . $value;
}
// rtrim($fields_string, '&');
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_ENCODING, 'UTF-8');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
return $result;
}
public function getSentencesFromJSON($json)
{
$sentencesArray = json_decode($json, true);
$sentences = "";
if (!$sentencesArray || !isset($sentencesArray[0]))
return json(['status'=>201,'data'=>'出错啦']);
//throw new \Exception("Google detected unusual traffic from your computer network, try again later (2 - 48 hours)");
foreach ($sentencesArray[0] as $s) {
$sentences .= isset($s[0]) ? $s[0] : '';
}
return $sentences;
}
tp5 谷歌翻译
最新推荐文章于 2022-05-27 11:47:36 发布