【问题标题】:Using the Azure Microsoft Translator API with PHP and cURL将 Azure Microsoft Translator API 与 PHP 和 cURL 一起使用
【发布时间】:2012-10-24 06:52:51
【问题描述】:

我正在尝试查找有关如何使新的 Azure 翻译 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

【问题讨论】:

  • 我正在寻找同样的东西。那里有可怕的 MSDN 文档......

标签: php windows api curl azure


【解决方案1】:

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

【讨论】:

  • 用户名和密码是ACC键吗?而这组代码会让它发挥作用吗?如此简短和甜美:O?
  • @RainbowHat:是的,还不错,虽然花了一些时间来浓缩它。
  • 不错 :) 与 microsoft smaple 相比,代码真的很不错,反正我使用的是 google API,Microsoft 不会接受我的中文字符。他们似乎无法聪明地阅读它
  • 我的 URL 太长了,有没有办法用 POST 做到这一点?
  • 我认为这个答案不再起作用了,今天令牌服​​务端点是不同的。更多信息在这里:docs.microsofttranslator.com/oauth-token.html
【解决方案2】:

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>";
?>

【讨论】:

    【解决方案3】:

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

    随着第 3 版的全面发布,现有的第 2 版将于 5 月 1 日起弃用。在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;
    

    【讨论】:

    • 当前这个 $json 是 { "error": { "code": 401000, "message": "由于凭据丢失或无效,请求未获得授权。" } } .
    • @IvanGanchev 您必须在第一行添加您自己的凭据 $key = "KEY_1"; // 这里的密钥!!!
    • 谢谢。我已经明白了。我正在寻找一个免费的解决方案,我认为它可以像那样使用(无需注册)。
    • @FurqanAhmed 我希望您能帮助您解决问题。我已将 KEY 1 值添加到上述代码中,但我仍然收到 { "error": { "code": 401000, "message": "The request is not authorized because credentials are missing or invalid." } } 信息。我的帐户有一个 KEY 2。这也需要吗?
    【解决方案4】:

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

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

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

    【讨论】:

      【解决方案5】:

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

      您可以通过在 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-11-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-13
        • 1970-01-01
        • 2014-01-06
        • 1970-01-01
        相关资源
        最近更新 更多