How to use Bing Translation API?

后端 未结 3 1096
醉梦人生
醉梦人生 2021-02-01 08:44

I am trying to use the Bing Translation API, but I am confused. There seems to be much possibilities (old and new ones) but I don\'t understand what I have to do.

Can so

3条回答
  •  隐瞒了意图╮
    2021-02-01 08:58

    Feel free to use this instructions (if you're using php):

    Define your keys

    $apis['azure']['id'] = 123456789
    $apis['azure']['key'] = 'abcde123456';
    

    Classes and functions

    class AccessTokenAuthentication {
        function getTokens($grantType, $scopeUrl, $clientID, $clientSecret, $authUrl){
            try {
                $ch = curl_init();
                $paramArr = array (
                    'grant_type'    => $grantType,
                    'scope'         => $scopeUrl,
                    'client_id'     => $clientID,
                    'client_secret' => $clientSecret
                );
                $paramArr = http_build_query($paramArr);
                curl_setopt($ch, CURLOPT_URL, $authUrl);
                curl_setopt($ch, CURLOPT_POST, TRUE);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $paramArr);
                curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                $strResponse = curl_exec($ch);
                $curlErrno = curl_errno($ch);
                if($curlErrno){
                    $curlError = curl_error($ch);
                    throw new Exception($curlError);
                }
                curl_close($ch);
                $objResponse = json_decode($strResponse);
                if($objResponse->error){
                    throw new Exception($objResponse->error_description);
                }
                return $objResponse->access_token;
            } catch (Exception $e) {
                echo "Exception-".$e->getMessage();
            }
        }
    }
    class HTTPTranslator {
        function curlRequest($url, $authHeader, $postData=''){
            $ch = curl_init();
            curl_setopt ($ch, CURLOPT_URL, $url);
            curl_setopt ($ch, CURLOPT_HTTPHEADER, array($authHeader,"Content-Type: text/xml"));
            curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE);
            curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, False);
            if($postData) {
                curl_setopt($ch, CURLOPT_POST, TRUE);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
            }
            $curlResponse = curl_exec($ch);
            $curlErrno = curl_errno($ch);
            if ($curlErrno) {
                $curlError = curl_error($ch);
                throw new Exception($curlError);
            }
            curl_close($ch);
            return $curlResponse;
        }
        function xmlLanguageCodes($languageCodes) {
            $requestXml = '';
            if(sizeof($languageCodes) > 0){
                foreach($languageCodes as $codes) {
                    $requestXml .= "$codes";
                }
            } else {
                throw new Exception('$languageCodes array is empty.');
            }
            $requestXml .= '';
            return $requestXml;
        }
    
        function xmlTranslateArray($fromLanguage,$toLanguage,$contentType,$inputStrArr) {
            $requestXml = "".
            "".
            "$fromLanguage". 
            "" .
                "" .
                "$contentType" .
                "" .
                "" .
                "" .
                "" .
            "" .
            "";
                foreach ($inputStrArr as $inputStr) {
                    $requestXml .= "$inputStr";
                }
            $requestXml .= "".
            "$toLanguage" .
            "";
            return $requestXml;
        }
    }
    
    function get_language_names($locale="en") {
        global $list, $apis;
        try {
            $clientID = $apis['azure']['id'];
            $clientSecret = $apis['azure']['key'];
            $authUrl = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13/";
            $scopeUrl = "http://api.microsofttranslator.com";
            $grantType = "client_credentials";
            $authObj = new AccessTokenAuthentication();
            $accessToken = $authObj->getTokens($grantType, $scopeUrl, $clientID, $clientSecret, $authUrl);
            $authHeader = "Authorization: Bearer ". $accessToken;
            foreach($list['translate'] as $k=>$iso) {
                $languageCodes[] = $k;
            }
            $url = "http://api.microsofttranslator.com/V2/Http.svc/GetLanguageNames?locale=$locale";
            $translatorObj = new HTTPTranslator();
            $requestXml = $translatorObj->xmlLanguageCodes($languageCodes);
            $curlResponse =$translatorObj->curlRequest($url, $authHeader, $requestXml);
            $xmlObj = simplexml_load_string($curlResponse);
            $i=0;
            foreach($xmlObj->string as $language) {
                $result[$languageCodes[$i]] = (string)$language;
                $i++;
            }
            return $result;
        } catch (Exception $e) {
            echo "Exception: " . $e->getMessage() . PHP_EOL;
        }
    }
    
    function get_translate($array, $from, $to, $html=false) {
        global $apis;
        try {
            $clientID = $apis['azure']['id'];
            $clientSecret = $apis['azure']['key'];
            $authUrl = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13/";
            $scopeUrl = "http://api.microsofttranslator.com";
            $grantType = "client_credentials";
            $authObj = new AccessTokenAuthentication();
            $accessToken = $authObj->getTokens($grantType, $scopeUrl, $clientID, $clientSecret, $authUrl);
            $authHeader = "Authorization: Bearer ". $accessToken;
    
            $fromLanguage = $from;
            $toLanguage = $to;
            $inputStrArr = array_values($array);
            if($html) {
                $contentType = 'text/html';
                foreach($inputStrArr as $k=>$item) {
                    $inputStrArr[$k] = htmlentities($inputStrArr[$k]);
                }
            } else {
                $contentType = 'text/plain';
            }
    
            $translatorObj = new HTTPTranslator();
            $requestXml = $translatorObj->xmlTranslateArray($fromLanguage,$toLanguage,$contentType,$inputStrArr);
            $translateUrl = "http://api.microsofttranslator.com/v2/Http.svc/TranslateArray";
            $curlResponse = $translatorObj->curlRequest($translateUrl, $authHeader, $requestXml);
    
            $xmlObj = simplexml_load_string($curlResponse);
            foreach($xmlObj->TranslateArrayResponse as $translatedArrObj){
                $result[] = (string)$translatedArrObj->TranslatedText;
            }
            return $result;
        } catch (Exception $e) {
            echo "Exception: " . $e->getMessage() . PHP_EOL;
        }
    }
    
    function get_translate_single($input, $from, $to, $html=false) {
        global $apis;
        try {
            $clientID = $apis['azure']['id'];
            $clientSecret = $apis['azure']['key'];
            $authUrl = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13/";
            $scopeUrl = "http://api.microsofttranslator.com";
            $grantType = "client_credentials";
            $authObj = new AccessTokenAuthentication();
            $accessToken = $authObj->getTokens($grantType, $scopeUrl, $clientID, $clientSecret, $authUrl);
            $authHeader = "Authorization: Bearer ". $accessToken;
    
            $fromLanguage = $from;
            $toLanguage = $to;
            if($html) {
                $contentType = 'text/html';
                $input = htmlentities($input);
            } else {
                $contentType = 'text/plain';
            }
    
            # params
            $params = "text=".urlencode($input)."&to=".$toLanguage."&from=".$fromLanguage;
            $translateUrl = "http://api.microsofttranslator.com/v2/Http.svc/Translate?".$params;
    
            # object
            $translatorObj = new HTTPTranslator();
            $curlResponse = $translatorObj->curlRequest($translateUrl, $authHeader);
    
            # interprets a string of XML into an object.
            $xmlObj = simplexml_load_string($curlResponse);
            foreach((array)$xmlObj[0] as $val){
                $result = $val;
            }
            return $result;
        } catch (Exception $e) {
            echo "Exception: " . $e->getMessage() . PHP_EOL;
        }
    }
    

    The calls

    echo get_translate_single('horse', 'en', 'es'); //this will print 'caballo'
    

    or

    echo get_translate(array('horse', 'house'), 'en', 'es'); //this will print array('caballo', 'casa')
    

    That's it, have fun and remember to follow the terms of service.

提交回复
热议问题