TranslateArray Method
Use the TranslateArray method to retrieve translations for multiple source texts.
| Method | Request URI |
|---|---|
| POST | http://api.microsofttranslator.com/V2/Http.svc/TranslateArray |
| Parameter | Description |
|---|---|
|
appId |
Required. If the Authorization header is used, leave the appid field empty else specify a string containing "Bearer" + " " + access token. |
|
from |
Optional. A string representing the language code to translate the text from. If left empty the response will include the result of language auto-detection. |
|
options |
Optional. A TranslateOptions element containing the values below. They are all optional and
default to the most common settings.
|
|
texts |
Required. An array containing the texts for translation. All strings must be of the same language. The total of all texts to be translated must not exceed 10000 characters. The maximum number of array elements is 2000. |
|
to |
Required. A string representing the language code to translate the text to. |
Note
|
|---|
|
The parameters must be sent in an alphabetical order as listed in the table. |
The following table describes required and optional request headers.
| Request Header | Description |
|---|---|
|
Authorization |
Required. Specify the the value of access_token in format "Bearer" + " " + Access Token Value |
The format of the request body is as follows
<TranslateArrayRequest>
<AppId />
<From>language-code</From>
<Options>
<Category xmlns="http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2" >string-value</Category>
<ContentType xmlns="http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2">text/plain</ContentType>
<ReservedFlags xmlns="http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2" />
<State xmlns="http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2" >int-value</State>
<Uri xmlns="http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2" >string-value</Uri>
<User xmlns="http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2" >string-value</User>
</Options>
<Texts>
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">string-value</string>
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">string-value</string>
</Texts>
<To>language-code</To>
</TranslateArrayRequest>
Returns a TranslateArrayResponse array. Each TranslateArrayResponse has the following elements
| Name | Description |
|---|---|
| TranslateArrayResponse |
A TranslateArrayResponse containing the following values:
|
The format of the response body is as follows
<ArrayOfTranslateArrayResponse xmlns="http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<TranslateArrayResponse>
<From>language-code</From>
<OriginalTextSentenceLengths xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<a:int>int-value</a:int>
</OriginalTextSentenceLengths>
<State/>
<TranslatedText>string-value</TranslatedText>
<TranslatedTextSentenceLengths xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<a:int>int-value</a:int>
</TranslatedTextSentenceLengths>
</TranslateArrayResponse>
</ArrayOfTranslateArrayResponse>
Note
|
|---|
|
Bing App ID is deprecated and is no longer supported. Please obtain an access token to use the Microsoft Translator API. For details, go here. |
Example
C#PHP
using System;
using System.IO;
using System.Net;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Web;
using System.Xml.Linq;
namespace MicrosoftTranslatorSdk.HttpSamples
{
class Program
{
static void Main(string[] args)
{
AdmAccessToken admToken;
string headerValue;
//Get Client Id and Client Secret from https://datamarket.azure.com/developer/applications/
//Refer obtaining AccessToken (http://msdn.microsoft.com/en-us/library/hh454950.aspx)
AdmAuthentication admAuth = new AdmAuthentication("clientID", "client secret");
try
{
admToken = admAuth.GetAccessToken();
// Create a header with the access_token property of the returned token
headerValue = "Bearer " + admToken.access_token;
TranslateArrayMethod(headerValue);
}
catch (WebException e)
{
ProcessWebException(e);
Console.WriteLine("Press any key to continue...");
Console.ReadKey(true);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine("Press any key to continue...");
Console.ReadKey(true);
}
}
private static void TranslateArrayMethod(string authToken)
{
string from = "en";
string to = "es";
string[] translateArraySourceTexts = { "The answer lies in machine translation.", "the best machine translation technology cannot always provide translations tailored to a site or users like a human ", "Simply copy and paste a code snippet anywhere " };
string uri = "http://api.microsofttranslator.com/v2/Http.svc/TranslateArray";
string body = "<TranslateArrayRequest>" +
"<AppId />" +
"<From>{0}</From>" +
"<Options>" +
" <Category xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" +
"<ContentType xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\">{1}</ContentType>" +
"<ReservedFlags xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" +
"<State xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" +
"<Uri xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" +
"<User xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" +
"</Options>" +
"<Texts>" +
"<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\">{2}</string>" +
"<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\">{3}</string>" +
"<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\">{4}</string>" +
"</Texts>" +
"<To>{5}</To>" +
"</TranslateArrayRequest>";
string reqBody = string.Format(body, from, "text/plain", translateArraySourceTexts[0], translateArraySourceTexts[1], translateArraySourceTexts[2], to);
// create the request
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Headers.Add("Authorization", authToken);
request.ContentType = "text/xml";
request.Method = "POST";
using (System.IO.Stream stream = request.GetRequestStream())
{
byte[] arrBytes = System.Text.Encoding.UTF8.GetBytes(reqBody);
stream.Write(arrBytes, 0, arrBytes.Length);
}
// Get the response
WebResponse response = null;
try
{
response = request.GetResponse();
using (Stream stream = response.GetResponseStream())
{
using (StreamReader rdr = new StreamReader(stream, System.Text.Encoding.UTF8))
{
// Deserialize the response
string strResponse = rdr.ReadToEnd();
Console.WriteLine("Result of translate array method is:");
XDocument doc = XDocument.Parse(@strResponse);
XNamespace ns = "http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2";
int soureceTextCounter = 0;
foreach (XElement xe in doc.Descendants(ns + "TranslateArrayResponse"))
{
foreach (var node in xe.Elements(ns + "TranslatedText"))
{
Console.WriteLine("\n\nSource text: {0}\nTranslated Text: {1}", translateArraySourceTexts[soureceTextCounter], node.Value);
}
soureceTextCounter++;
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey(true);
}
}
}
catch
{
throw;
}
finally
{
if (response != null)
{
response.Close();
response = null;
}
}
}
private static void ProcessWebException(WebException e)
{
Console.WriteLine("{0}", e.ToString());
// Obtain detailed error information
string strResponse = string.Empty;
using (HttpWebResponse response = (HttpWebResponse)e.Response)
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader sr = new StreamReader(responseStream, System.Text.Encoding.ASCII))
{
strResponse = sr.ReadToEnd();
}
}
}
Console.WriteLine("Http status code={0}, error message={1}", e.Status, strResponse);
}
}
}
Goto Top
<?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 getTokens($grantType, $scopeUrl, $clientID, $clientSecret, $authUrl){
try {
//Initialize the Curl Session.
$ch = curl_init();
//Create the request Array.
$paramArr = array (
'grant_type' => $grantType,
'scope' => $scopeUrl,
'client_id' => $clientID,
'client_secret' => $clientSecret
);
//Create an Http Query.//
$paramArr = http_build_query($paramArr);
//Set the Curl URL.
curl_setopt($ch, CURLOPT_URL, $authUrl);
//Set HTTP POST Request.
curl_setopt($ch, CURLOPT_POST, TRUE);
//Set data to POST in HTTP "POST" Operation.
curl_setopt($ch, CURLOPT_POSTFIELDS, $paramArr);
//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);
//Execute the cURL session.
$strResponse = 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 the Curl Session.
curl_close($ch);
//Decode the returned JSON string.
$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 {
/*
* Create and execute the HTTP CURL request.
*
* @param string $url HTTP Url.
* @param string $authHeader Authorization Header string.
* @param string $postData Data to post.
*
* @return string.
*
*/
function curlRequest($url, $authHeader, $postData=''){
//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"));
//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);
if($postData) {
//Set HTTP POST Request.
curl_setopt($ch, CURLOPT_POST, TRUE);
//Set data to POST in HTTP "POST" Operation.
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
}
//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;
}
/*
* Create Request XML Format.
*
* @param string $fromLanguage Source language Code.
* @param string $toLanguage Target language Code.
* @param string $contentType Content Type.
* @param string $inputStrArr Input String Array.
*
* @return string.
*/
function createReqXML($fromLanguage,$toLanguage,$contentType,$inputStrArr) {
//Create the XML string for passing the values.
$requestXml = "<TranslateArrayRequest>".
"<AppId/>".
"<From>$fromLanguage</From>".
"<Options>" .
"<Category xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" .
"<ContentType xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\">$contentType</ContentType>" .
"<ReservedFlags xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" .
"<State xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" .
"<Uri xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" .
"<User xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" .
"</Options>" .
"<Texts>";
foreach ($inputStrArr as $inputStr)
$requestXml .= "<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\">$inputStr</string>" ;
$requestXml .= "</Texts>".
"<To>$toLanguage</To>" .
"</TranslateArrayRequest>";
return $requestXml;
}
}
try {
//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->getTokens($grantType, $scopeUrl, $clientID, $clientSecret, $authUrl);
//Create the authorization Header string.
$authHeader = "Authorization: Bearer ". $accessToken;
//Set the params.//
$fromLanguage = "en";
$toLanguage = "de";
$inputStrArr = array("The answer lies in machine translation.", "the best machine translation technology cannot always provide translations tailored to a site or users like a human.");
$contentType = 'text/plain';
//Create the Translator Object.
$translatorObj = new HTTPTranslator();
//Get the Request XML Format.
$requestXml = $translatorObj->createReqXML($fromLanguage,$toLanguage,$contentType,$inputStrArr);
//HTTP TranslateMenthod URL.
$translateUrl = "http://api.microsofttranslator.com/v2/Http.svc/TranslateArray";
//Call HTTP Curl Request.
$curlResponse = $translatorObj->curlRequest($translateUrl, $authHeader, $requestXml);
//Interprets a string of XML into an object.
$xmlObj = simplexml_load_string($curlResponse);
$i=0;
echo "<table border=2px>";
echo "<tr>";
echo "<td><b>From $fromLanguage</b></td><td><b>To $toLanguage</b></td>";
echo "</tr>";
foreach($xmlObj->TranslateArrayResponse as $translatedArrObj){
echo "<tr><td>".$inputStrArr[$i]."</td><td>". $translatedArrObj->TranslatedText."</td></tr>";
$i++;
}
echo "</table>";
} catch (Exception $e) {
echo "Exception: " . $e->getMessage() . PHP_EOL;
}
Note