<?php
/**
 * Note: *
 * User: Liu
 * Date: 2020/5/26
 * Time: 22:46
 */
class Google
{
    const API_URL = "http://translate.google.cn/translate_a/single";

    /**
     * 中文转英文
     * @param $string
     * @return mixed
     * @throws Exception
     */
    public static function zh2en($string)
    {
        $params = [
            'client' => 'gtx',
            'dt' => 't',
            'dj' => '1',
            'ie' => 'UTF-8',
            'sl' => 'zh_CN',//input
            'tl' => 'en',// output
            'q' => $string,
        ];
        $response = self::requestGet(self::API_URL, $params);
        $response = json_decode($response, true);
        $result = '';
        foreach ($response['sentences'] as $value) {
            $result .= $value['trans'];
        }
        return $result;
    }

    /**
     * 英文转中文
     * @param $string
     * @return mixed
     * @throws Exception
     */
    public static function en2zh($string)
    {
        $params = [
            'client' => 'gtx',
            'dt' => 't',
            'dj' => '1',
            'ie' => 'UTF-8',
            'sl' => 'en',//input
            'tl' => 'zh_CN',// output
            'q' => $string,
        ];
        $response = self::requestGet(self::API_URL, $params);
        $response = json_decode($response, true);
        $result = '';
        foreach ($response['sentences'] as $value) {
            $result .= $value['trans'];
        }
        return $result;
    }

    /**
     * @param $api
     * @param string $data
     * @return bool|string
     * @throws Exception
     */
    public static function requestGet($api, $data = '')
    {
        if (!empty($data) && is_array($data)) {
            $api .= '?'.http_build_query($data);
        }
        $ch = curl_init($api);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
        curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        //curl_setopt($ch, CURLOPT_POST, TRUE);
        //curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $response = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);
        if (empty($error)) {
            return $response;
        }
        throw new \Exception($error);
    }
}