<?php
/**
 * Note: *
 * User: Liu
 * Date: 2020/5/26
 * Time: 22:46
 */
class Youdao
{
    const API_URL = 'http://fanyi.youdao.com/translate';

    /**
     * 中文转英文
     * @param $string
     * @return mixed
     * @throws Exception
     */
    public static function zh2en($string)
    {
        $params = [
            'doctype' => 'json',
            'type' => 'ZH_CN2EN',
            'i' => $string,
        ];
        $response = self::requestGet(self::API_URL, $params);
        $response = json_decode($response, true);
        $result = "";
        foreach ($response['translateResult'][0] as $value) {
            $result .= $value['tgt'];
        }
        return $result;
    }

    /**
     * 英文转中文
     * @param $string
     * @return mixed
     * @throws Exception
     */
    public static function en2zh($string)
    {
        $params = [
            'doctype' => 'json',
            'type' => 'EN2ZH_CN',
            'i' => $string,
        ];
        $response = self::requestGet(self::API_URL, $params);
        $response = json_decode($response, true);
        return $response['translateResult'][0][0]['tgt'];
    }

    /**
     * @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);
    }
}