Using the Azure Microsoft Translator API with PHP and cURL Using the Azure Microsoft Translator API with PHP and cURL curl curl

Using the Azure Microsoft Translator API with PHP and cURL


I know this question is a few months old, but since I was dealing with this today I thought I would share my working code. Here's a simple example of how to use the Translate Method in the Microsoft Translator V2 API using your primary account key and basic authentication. You can obtain your primary account key here.

// Prepare variables$text = urlencode('Hello world.');$from = 'en';$to = 'es';// Prepare cURL command$key = 'YOUR_PRIMARY_ACCOUNT_KEY';$ch = curl_init('https://api.datamarket.azure.com/Bing/MicrosoftTranslator/v1/Translate?Text=%27'.$text.'%27&From=%27'.$from.'%27&To=%27'.$to.'%27');curl_setopt($ch, CURLOPT_USERPWD, $key.':'.$key);curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);// Parse the XML response$result = curl_exec($ch);$result = explode('<d:Text m:type="Edm.String">', $result);$result = explode('</d:Text>', $result[1]);$result = $result[0];echo $result;

This should return:

Hola mundo.

For more information on the GET parameters, see the MSDN documentation.


The Microsoft DataMarket Translator API will stop working 3/31/17: https://datamarket.azure.com/dataset/bing/microsofttranslator

So I made a new sample PHP/cURL code that will work in the future:

<?php // 4.01.17 AZURE Text Translation API 2017 - PHP Code Example - Cognitive Services with CURL http://www.aw6.de/azure/// Get your key from: http://docs.microsofttranslator.com/text-translate.html// Put your parameters here:$azure_key = "KEY_1";  // !!! TODO: secret key here !!!$fromLanguage = "en";  // Translator Language Codes: https://msdn.microsoft.com/de-de/library/hh456380.aspx$toLanguage = "de";$inputStr = "AZURE - The official documentation and examples for PHP are useless.";// and leave the rest of the code as it is ;-)// Get the AZURE tokenfunction 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;}// Request the translationfunction curlRequest($url){    $ch = curl_init();    curl_setopt($ch, CURLOPT_URL, $url);    curl_setopt($ch, CURLOPT_HTTPHEADER, "Content-Type: text/xml");    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, False);    $curlResponse = curl_exec($ch);    curl_close($ch);    return $curlResponse;}// Get the translation$accessToken = getToken($azure_key);$params = "text=" . urlencode($inputStr) . "&to=" . $toLanguage . "&from=" . $fromLanguage . "&appId=Bearer+" . $accessToken;$translateUrl = "http://api.microsofttranslator.com/v2/Http.svc/Translate?$params";$curlResponse = curlRequest($translateUrl);$translatedStr = simplexml_load_string($curlResponse);// Display the translated text on the web page:echo "<p>From " . $fromLanguage . ": " . $inputStr . "<br>";echo "To " . $toLanguage . ": " . $translatedStr . "<br>";echo date(r) . "<p>";?>


Version 3 is out there, support for version 2 is supported until 04/30/2019.

Following the general availability of Version 3, the existing Version 2 will be deprecated starting May 1st. V2 will remain supported until 04/30/2019.

So sample PHP/cURL code for api v3

<?php$key =  "KEY_1";  //  secret key here !!!$host = "https://api.cognitive.microsofttranslator.com";$path = "/translate?api-version=3.0";$params = "&to=en&from=ar";$text = "Hello, world!";$requestBody = array (    array (        'Text' => $text,    ),);$content = json_encode($requestBody);if (!function_exists('com_create_guid')) {  function com_create_guid() {    return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',        mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),        mt_rand( 0, 0xffff ),        mt_rand( 0, 0x0fff ) | 0x4000,        mt_rand( 0, 0x3fff ) | 0x8000,        mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )    );  }}$curl_headers = array(    'Content-type: application/json',    'Content-length: '. strlen($content) ,    'Ocp-Apim-Subscription-Key: '. $key ,    'X-ClientTraceId: '. com_create_guid() );$url = $host . $path . $params;$ch = curl_init();$curl_content = array('content',$content);curl_setopt($ch, CURLOPT_URL,$url);curl_setopt($ch, CURLOPT_POST, 1);curl_setopt($ch, CURLOPT_HTTPHEADER, $curl_headers);curl_setopt($ch, CURLOPT_POSTFIELDS, $content);// Receive server response ...curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);$result = curl_exec($ch);curl_close ($ch);// Note: We convert result, which is JSON, to and from an object so we can pretty-print it.// We want to avoid escaping any Unicode characters that result contains. See:// http://php.net/manual/en/function.json-encode.php$json = json_encode(json_decode($result), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);echo $json;