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

使用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

  • 写回答

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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?