doulu5717
2012-11-04 01:08
浏览 90
已采纳

使用Azure Microsoft Translator API与PHP和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

图片转代码服务由CSDN问答提供 功能建议

我试图找到一个简单的教程,介绍如何让新的Azure Translation API与PHP和Curl一起使用。

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

我已经创建了我的用户帐户 并注册了一份申请。

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

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

新Bing API PHP示例无效

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

4条回答 默认 最新

  • dpspn60064 2013-05-10 20:40
    已采纳

    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.

    打赏 评论
  • dongliao3450 2017-01-05 19:42

    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>";
    ?>
    
    打赏 评论
  • dsfds2353 2017-01-21 00:26

    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.

    打赏 评论
  • dougui4325 2018-10-31 04:46

    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;
    
    打赏 评论

相关推荐 更多相似问题