Quickstart for Microsoft Translator Text API with PHP

This article shows you how to use the Translate method to translate text from one language to another. For information on how to use the other Translator Text APIs, see this Github repository.


You will need PHP 5.6.x to run this code.

You must have a Cognitive Services API account with Microsoft Translator Text API. You will need a paid subscription key from your Azure dashboard.

Translate text

The following code translates source text from one language to another, using the Translate method.

  1. Create a new PHP project in your favorite IDE.
  2. Add the code provided below.
  3. Replace the key value with an access key valid for your subscription.
  4. Run the program.

// NOTE: Be sure to uncomment the following line in your php.ini file.
// ;extension=php_openssl.dll

// **********************************************
// *** Update or verify the following values. ***
// **********************************************

// Replace the subscriptionKey string value with your valid subscription key.
$key = 'ENTER KEY HERE';

$host = "https://api.microsofttranslator.com";
$path = "/V2/Http.svc/Translate";

$target = "fr-fr";
$text = "Hello";

$params = '?to=' . $target . '&text=' . urlencode($text);

$content = '';

function Translate ($host, $path, $key, $params, $content) {

    $headers = "Content-type: text/xml\r\n" .
        "Ocp-Apim-Subscription-Key: $key\r\n";

    // NOTE: Use the key 'http' even if you are making an HTTPS request. See:
    // http://php.net/manual/en/function.stream-context-create.php
    $options = array (
        'http' => array (
            'header' => $headers,
            'method' => 'GET'
    $context  = stream_context_create ($options);
    $result = file_get_contents ($host . $path . $params, false, $context);
    return $result;

$result = Translate ($host, $path, $key, $params, $content);

echo $result;

Translate response

A successful response is returned in XML, as shown in the following example:

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">Salut</string>

Next steps

See also

Translator Text overview
API Reference