tp5 谷歌翻译

使用方法:
此次是中文转英文
$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;
	}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

时间轴-小文同学

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值