简体   繁体   English

将 Azure Microsoft Translator API 与 PHP 和 cURL 结合使用

[英]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.我试图找到一个关于如何让新的 Azure 翻译 API 与 PHP 和 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.我正在处理这些示例,但我无法弄清楚如何将它们用作简单的 PHP 函数。

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

New Bing API PHP example doesnt work 新的 Bing API PHP 示例不起作用

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.下面是一个简单示例,说明如何使用主帐户密钥和基本身份验证在 Microsoft Translator V2 API 中使用翻译方法。 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 .有关GET参数的更多信息,请参阅MSDN 文档

The Microsoft DataMarket Translator API will stop working 3/31/17: https://datamarket.azure.com/dataset/bing/microsofttranslator Microsoft DataMarket Translator API 将于 17 年 3 月 31 日停止工作: https ://datamarket.azure.com/dataset/bing/microsofttranslator

So I made a new sample PHP/cURL code that will work in the future:所以我制作了一个新的示例 PHP/cURL 代码,它将在未来工作:

<?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.版本 3 已经发布,对版本 2 的支持一直持续到 2019 年 4 月 30 日。

Following the general availability of Version 3, the existing Version 2 will be deprecated starting May 1st.在第 3 版普遍可用后,现有的第 2 版将从 5 月 1 日起弃用。 V2 will remain supported until 04/30/2019 . V2 将一直支持到04/30/2019

So sample PHP/cURL code for api v3因此,api v3 的示例 PHP/cURL 代码

<?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新 Azure 转换器 API 的官方代码在这里: 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.但是该代码包含无用的额外参数$authHeader ,该参数$authHeader发布的代码中删除。

It seems that only access token method has been modified in the new Azure API.在新的 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.您可以通过在 Azure 门户的“密钥和终结点”中检查位置来执行此操作。

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.在这个例子中,我没有定义“From”参数,因为我的应用程序不需要它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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