使用Azure Microsoft Translator API与PHP和cURL

时间:2012-11-04 01:08:14

标签: php windows api curl azure

我正在尝试找到一个简单的教程,介绍如何使用新的Azure Translation API来使用PHP和Curl。

有没有人有一个简单函数的示例代码,可以调用它来执行字符串的转换?

我已经创建了我的用户帐户并注册了一个应用程序。

我正在处理这些示例,但我无法弄清楚如何将它们用作简单的PHP函数。

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

New Bing API PHP example doesnt work

5 个答案:

答案 0 :(得分:11)

我知道这个问题已经有几个月了,但是因为今天我正在处理这个问题,所以我想我会分享我的工作代码。以下是如何使用主帐户密钥和基本身份验证在Microsoft Translator V2 API中使用翻译方法的简单示例。您可以获取主要帐户密钥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;

这应该返回:

Hola mundo.

有关GET参数的详细信息,请参阅MSDN documentation

答案 1 :(得分:5)

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

所以我制作了一个新的样本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>";
?>

答案 2 :(得分:1)

版本3可用,直到2019年4月30日为止都支持版本2。

  

在第3版全面上市之后,将从5月1日开始弃用现有的第2版。在04/30/2019之前,将一直支持V2。

因此,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;

答案 3 :(得分:0)

新Azure转换程序API的官方代码位于:https://github.com/MicrosoftTranslator/HTTP-Code-Samples/blob/master/PHP/PHPAzureToken.php

但代码中包含无用的额外参数$authHeader,该参数已从@Andreas发布的代码中删除。

似乎只在新的Azure API中修改了访问令牌方法。

答案 4 :(得分:0)

对于当前版本,您需要定义资源位置。

您可以通过在 Azure 门户中的“密钥和终结点”中检查位置来执行此操作。

你可以通过简单地在上面的代码中添加两行来添加它,给你这样的东西。

$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;

在这个例子中,我没有定义“From”参数,因为我的应用程序不需要它。