简体   繁体   中英

Using the Azure Microsoft Translator API with PHP and cURL

I am trying to find a simple tutorial on how to get the new Azure Translation API to work with PHP and Curl.

Does anyone have example code of a simple function that can be called to perform a translation of a string?

I have already created my user account and registered an application.

I am working off of these examples but I am not able to figure out how to use them as a simple PHP function.

http://wangpidong.blogspot.ca/2012/04/how-to-use-new-bing-translator-api-with.html

New Bing API PHP example doesnt work

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 token
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;
}
// Request the translation
function 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;

The official code of the new Azure translator API is here : https://github.com/MicrosoftTranslator/HTTP-Code-Samples/blob/master/PHP/PHPAzureToken.php

But the code contains useless extra parameter $authHeader which is removed from the code posted by @Andreas.

It seems that only access token method has been modified in the new Azure API.

For the current version you will need to define the resource location.

You can do this by checking Location in "Keys and Endpoints" in the Azure portal.

And you can add it by simply adding two lines to the code above, to giev you somethinglike this.

$key =  "YOUR_API_KEY";  //  secret key here
$location = "YOUR_LOCATION"; // service location here 

$host = "https://api.cognitive.microsofttranslator.com";
$path = "/translate?api-version=3.0";

$params = "&to=en";
$requestBody = array(
    array(
        'text' => 'Mañanas',
    ),
);
$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(

    'Ocp-Apim-Subscription-Key: ' . $key, // API KEY
    'Ocp-Apim-Subscription-Region: '. $location, // LOCATION 

    'Content-type: application/json',
    'Content-length: ' . strlen($content),
    '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);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);

$json = json_encode(json_decode($result), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
echo $json;

In this example I do not define the 'From' param, as I do not need it for my application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM