3

我正在尝试查找有关如何使新的 Azure 翻译 API 与 PHP 和 Curl 一起使用的简单教程。

有没有人有可以调用来执行字符串翻译的简单函数的示例代码?

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

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

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

新的 Bing API PHP 示例不起作用

4

5 回答 5

11

我知道这个问题已经存在几个月了,但是因为我今天正在处理这个问题,所以我想我会分享我的工作代码。下面是一个简单示例,说明如何使用您的主帐户密钥和基本身份验证在 Microsoft Translator V2 API 中使用 Translate 方法。您可以在此处获取您的主帐户密钥。

// 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 文档

于 2013-05-10T20:40:36.607 回答
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>";
?>
于 2017-01-05T19:42:20.007 回答
4

版本 3 已发布,支持版本 2 直到 2019 年 4 月 30 日。

随着第 3 版的全面发布,现有的第 2 版将于 5 月 1 日起弃用。V2 将一直支持到2019年 4 月 30 日。

因此,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;
于 2018-10-31T04:46:55.327 回答
0

新 Azure 翻译 API 的官方代码在这里:https ://github.com/MicrosoftTranslator/HTTP-Code-Samples/blob/master/PHP/PHPAzureToken.php

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

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

于 2017-01-21T00:26:48.503 回答
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”参数,因为我的应用程序不需要它。

于 2021-04-29T10:55:05.087 回答