2017-03-07 146 views
2

我想根據API reference從Microsoft Translator API使用/ getTranslations方法獲得給定單詞的多個可靠翻譯。不幸的是,github上提供的示例已過時:Outdated Example。我設法更新了getTokens函數和對它的引用,並且我確實得到了一個翻譯,但我需要多個。使用Microsoft Translator API獲取多個翻譯

有沒有人有一個工作示例/知道我的代碼的修復?

這裏是我的代碼:微軟翻譯的V2 API中

<?php 
class AccessTokenAuthentication { 
    /* 
    * Get the access token. 
    * 
    * @param string $grantType Grant type. 
    * @param string $scopeUrl  Application Scope URL. 
    * @param string $clientID  Application client ID. 
    * @param string $clientSecret Application client ID. 
    * @param string $authUrl  Oauth Url. 
    * 
    * @return string. 
    */ 
function getToken($azure_key) 
{ 
    $url = 'https://api.cognitive.microsoft.com/sts/v1.0/issueToken'; 
    $ch = curl_init(); 
    $data_string = json_encode('{body}'); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); 
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
      'Content-Type: application/json', 
      'Content-Length: ' . strlen($data_string), 
      'Ocp-Apim-Subscription-Key: ' . $azure_key 
     ) 
    ); 
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_HEADER, false); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
    $strResponse = curl_exec($ch); 
    curl_close($ch); 
    return $strResponse; 
} 
} 
/* 
* Class:HTTPTranslator 
* 
* Processing the translator request. 
*/ 
Class HTTPTranslator { 
    /* 
    * Create and execute the HTTP CURL request. 
    * 
    * @param string $url  HTTP Url. 
    * @param string $authHeader Authorization Header string. 
    * 
    * @return string. 
    * 
    */ 
    function curlRequest($url, $authHeader) { 
     //Initialize the Curl Session. 
     $ch = curl_init(); 
     //Set the Curl url. 
     curl_setopt ($ch, CURLOPT_URL, $url); 
     //Set the HTTP HEADER Fields. 
     curl_setopt ($ch, CURLOPT_HTTPHEADER, array($authHeader,"Content-Type: text/xml", 'Content-Length: 0')); 
     //CURLOPT_RETURNTRANSFER- TRUE to return the transfer as a string of the return value of curl_exec(). 
     curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE); 
     //CURLOPT_SSL_VERIFYPEER- Set FALSE to stop cURL from verifying the peer's certificate. 
     curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, False); 
     //Set HTTP POST Request. 
     curl_setopt($ch, CURLOPT_POST, TRUE); 
     //Execute the cURL session. 
     $curlResponse = curl_exec($ch); 
     //Get the Error Code returned by Curl. 
     $curlErrno = curl_errno($ch); 
     if ($curlErrno) { 
      $curlError = curl_error($ch); 
      throw new Exception($curlError); 
     } 
     //Close a cURL session. 
     curl_close($ch); 
     return $curlResponse; 
    } 
} 
try { 
    //Azure Key 
    $azure_key  = "<my key>"; 
    //Client ID of the application. 
    //$clientID  = "clientId"; 
    //Client Secret key of the application. 
    //$clientSecret = "ClientSecret"; 
    //OAuth Url. 
    $authUrl  = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13/"; 
    //Application Scope Url 
    //$scopeUrl  = "http://api.microsofttranslator.com"; 
    //Application grant type 
    //$grantType = "client_credentials"; 
    //Create the AccessTokenAuthentication object. 
    $authObj  = new AccessTokenAuthentication(); 
    //Get the Access token. 
    $accessToken = $authObj->getToken($azure_key); 
    //Create the authorization Header string. 
    $authHeader = "Authorization: Bearer ". $accessToken; 
    //Set the Params. 
    $inputStr  = "get"; 
    $fromLanguage = "en"; 
    $toLanguage  = "de"; 
    //$user   = 'TestUser'; 
    $category  = "general"; 
    //$uri    = null; 
    $contentType = "text/plain"; 
    $maxTranslation = 5; 
    //Create the string for passing the values through GET method. 
    $params = "from=$fromLanguage". 
       "&to=$toLanguage". 
       "&maxTranslations=$maxTranslation". 
       "&text=".urlencode($inputStr). 
       //"&user=$user". 
       //"&uri=$uri". 
       "&contentType=$contentType"; 
    //HTTP getTranslationsMethod URL. 
    $getTranslationUrl = "http://api.microsofttranslator.com/V2/Http.svc/GetTranslations?$params"; 
    //Create the Translator Object. 
    $translatorObj = new HTTPTranslator(); 
    //Call the curlRequest. 
    $curlResponse = $translatorObj->curlRequest($getTranslationUrl, $authHeader); 
    //Interprets a string of XML into an object. 
    $xmlObj = simplexml_load_string($curlResponse); 
    $translationObj = $xmlObj->Translations; 
    $translationMatchArr = $translationObj->TranslationMatch; 
    print_r($translationMatchArr); 
    echo "Get Translation For <b>$inputStr</b>"; 
    echo "<table border ='2px'>"; 
    echo "<tr><td><b>Count</b></td><td><b>MatchDegree</b></td> 
     <td><b>Rating</b></td><td><b>TranslatedText</b></td></tr>"; 
    foreach($translationMatchArr as $translationMatch) { 
     echo "<tr><td>$translationMatch->Count</td><td>$translationMatch->MatchDegree</td><td>$translationMatch->Rating</td> 
      <td>$translationMatch->TranslatedText</td></tr>"; 
    } 
    echo "</table></br>"; 
} catch (Exception $e) { 
    echo "Exception: " . $e->getMessage() . PHP_EOL; 
} 

回答

0

的GetTranslations()和GetTranslationsArray()方法包括一個可選的布爾標誌 「IncludeMultipleMTAlternatives」。 即使沒有可用的CTF條目數量,該方法也會返回到maxTranslations選項,其中delta是從翻譯器引擎的n最佳列表中提供的。機器生成的替代品的評分爲0。人爲策劃的替代品的評分爲1或更高。

+0

感謝您的回答,這不是新的開發者文檔中提到。然而,在$ params中添加「&IncludeMultipleMTAlternatives = true」(它反過來被添加到請求URL中)似乎沒有任何改變,但我仍然只獲得一個翻譯作爲響應。 –

1

我解決了這個問題是這樣的: (IncludeMultipleMTAlternatives桅杆先在選項部分)

<GetTranslationsArrayRequest> 
 
    <AppId></AppId> 
 
    <From>en</From> 
 
    <Options> 
 
    <IncludeMultipleMTAlternatives xmlns="http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2">true</IncludeMultipleMTAlternatives> 
 
    <State xmlns="http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2">777</State> 
 
    </Options> 
 
    <Texts> 
 
    \t <string xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">world</string> 
 
    \t <string xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">sun</string> 
 
    </Texts> 
 
    <To>ru</To> 
 
    <MaxTranslations>10</MaxTranslations> 
 
</GetTranslationsArrayRequest>