Using Microsoft Translator with PHP


In the first article in this series you saw how to sign up for the Microsoft Translator service with Windows Azure marketplace, and how, in particular to get your ClientID and ClientSecret. In this article you’ll see how to use them with PHP in order to provide translation services. If you’re already familiar with, or already have a PHP environment set up, you can skip down to Step 2 and see how to implement a translator site. If not, go ahead with Step 1 and you’ll see how easy WebMatrix makes it for you to create a new PHP site.

Step 1 – Create a PHP Site with WebMatrix

If you don’t already have a PHP environment set up, I recommend the excellent, free, WebMatrix tool from Microsoft. This will allow you to create and edit PHP-based sites on your Windows computer, and upload them to any PHP-enabled web host. You can get WebMatrix at http://www.microsoft.com/web/webmatrix.

Once you’ve installed WebMatrix, launch it and you’ll see the Welcome Screen:

image

From here, select ‘Templates’, and select the ‘Empty Site’ template, and call it ‘translate’ to create a new, empty web site. Use the ‘Files’ tab on the left to see the files in your web site. You’ll notice that you have a Default.cshtml page, as well as a couple of folders. These are used for the ASP.NET Web Pages technology, so as you aren’t going to be using those in this site, you can feel free to delete them

Next, you’ll need to enable PHP on your site. To do this, select the ‘Site’ tab on the left, and select the ‘Settings’ entry above it. You’ll then see a checkbox to ‘Enable PHP’ on your site:

image

Once you’ve done this, if you don’t have PHP already installed on your PC, you’ll see a dialog requesting which version you want. Pick the most recent (at time of writing it is PHP 5.3.13), and install it. WebMatrix does all the hard work of figuring out dependencies, downloading them, and installing them on your local web server.

Once everything is done, go back to the Files tab, and create a new PHP file. Call it ‘index.php’. Remove the code that WebMatrix created for you, and replace it with the following:

<?php
   phpinfo();
?>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Now run the web site, and you should see something like this, showing that PHP is running.

image

You’re now ready to write a PHP-based translator site!

Step 2. Implement the PHP Helper classes

To keep the PHP for our translation page relatively simple, it’s a good idea to separate the functionality into modules, and these modules can then be imported into the translation page.

Authenticating against the Windows Azure Marketplace.

The Microsoft Translator API requires you to authenticate against the Windows Azure Marketplace before you can use it. Doing this gives you a token that you can pass to the Microsoft Translator service in order to perform a translation. The code to do this will be implemented in a class called ‘AccessTokenAuthentication’, which in turn you’ll import into your translation page.

Here’s the code for AccessTokenAuthentication.php:

<?php
class AccessTokenAuthentication {
    /*
     * Get the access token.
     *
     * @param string $grantType    Grant type.
     * @param string $scopeUrl     Application Scope URL.
     * @param string $clientID     Application client ID.
     * @param string $clientSecret Application client ID.
     * @param string $authUrl      Oauth Url.
     *
     * @return string.
     */
    function getTokens($grantType, $scopeUrl, $clientID, $clientSecret, $authUrl){
        try {
            //Initialize the Curl Session.
            $ch = curl_init();
            //Create the request Array.
            $paramArr = array (
                 'grant_type'    => $grantType,
                 'scope'         => $scopeUrl,
                 'client_id'     => $clientID,
                 'client_secret' => $clientSecret
            );
            //Create an Http Query.//
            $paramArr = http_build_query($paramArr);
            //Set the Curl URL.
            curl_setopt($ch, CURLOPT_URL, $authUrl);
            //Set HTTP POST Request.
            curl_setopt($ch, CURLOPT_POST, TRUE);
            //Set data to POST in HTTP "POST" Operation.
            curl_setopt($ch, CURLOPT_POSTFIELDS, $paramArr);
            //CURLOPT_RETURNTRANSFER- TRUE to return the transfer as a string of the return value of curl_exec().
            curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE);
            //CURLOPT_SSL_VERIFYPEER- Set FALSE to stop cURL from verifying the peer's certificate.
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            //Execute the  cURL session.
            $strResponse = curl_exec($ch);
            //Get the Error Code returned by Curl.
            $curlErrno = curl_errno($ch);
            if($curlErrno){
                $curlError = curl_error($ch);
                throw new Exception($curlError);
            }
            //Close the Curl Session.
            curl_close($ch);
            //Decode the returned JSON string.
            $objResponse = json_decode($strResponse);
            if ($objResponse->error){
                throw new Exception($objResponse->error_description);
            }
            return $objResponse->access_token;
        } catch (Exception $e) {
            echo "Exception-".$e->getMessage();
        }
    }
}
?>

Calling the Translator HTTP API.

The other helper class handles the communication with the translator API for you. It uses PHP’s CURL functionality to synchronously communicate with an HTTP Web Service.

Here’s the code for HttpTranslator.php:

<?php
/*
 * Class:HTTPTranslator
 *
 * Processing the translator request.
 */
Class HTTPTranslator {
    /*
     * Create and execute the HTTP CURL request.
     *
     * @param string $url        HTTP Url.
     * @param string $authHeader Authorization Header string.
     * @param string $postData   Data to post.
     *
     * @return string.
     *
     */
    function curlRequest($url, $authHeader) {
        //Initialize the Curl Session.
        $ch = curl_init();
        //Set the Curl url.
        curl_setopt ($ch, CURLOPT_URL, $url);
        //Set the HTTP HEADER Fields.
        curl_setopt ($ch, CURLOPT_HTTPHEADER, array($authHeader,"Content-Type: text/xml"));
        //CURLOPT_RETURNTRANSFER- TRUE to return the transfer as a string of the return value of curl_exec().
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE);
        //CURLOPT_SSL_VERIFYPEER- Set FALSE to stop cURL from verifying the peer's certificate.
        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, False);
        //Execute the  cURL session.
        $curlResponse = curl_exec($ch);
        //Get the Error Code returned by Curl.
        $curlErrno = curl_errno($ch);
        if ($curlErrno) {
            $curlError = curl_error($ch);
            throw new Exception($curlError);
        }
        //Close a cURL session.
        curl_close($ch);
        return $curlResponse;
    }
}
?>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Step 3. Build your Translator Site

Now that you have the helper classes implemented, creating a translator page is very straightforward. Create a new PHP page called ‘translate.php’ and edit it’s HTML to look like this:

<!DOCTYPE html>

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
        <form action="translate.php" method="post">
            Text to translate: <input type="text" name="txtToTranslate" value="<?php echo($inputStr); ?>"  />
            <input type="submit" value="Translate">
            
        </form>
        <p>Translated Text: <?php echo($translatedStr); ?></p>
    </body>
</html>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

This creates a simple HTML form that renders a text box and a translate button, along with a paragraph for the translated text. You’ll notice that there are 2 pieces of PHP here, one which echoes back the input string, and one which echoes back the translated string. You haven’t set up these variables yet, so if you look at the page, both will be blank.

image

And that’s ok, because we haven’t done any translation yet. Look carefully at the form declaration, and you will see this:

 <form action="translate.php" method="post">

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

When the user submits an HTML form, the page specified in the ‘action’ parameter is called. But as the page specified here is translate.php, then pressing submit will post back to the same page. This is a really useful technique, because it allows us to do the translation, and then refresh the form with the translated text.

To do this, edit translate.php, and add the following PHP code at the top:

<?php

if('POST' == $_SERVER['REQUEST_METHOD'])
{
    include 'HttpTranslator.php';
    include 'AccessTokenAuthentication.php';

    try {
        //Client ID of the application.
        $clientID       = "fc9827b7-1512-44d3-93b4-5a088ad4d4b9";
        //Client Secret key of the application.
        $clientSecret = "f4xHZtBN7o9g6V5Uuyfy0mtAzpWDRjMTpXEkMjwu1Fg=";
        //OAuth Url.
        $authUrl      = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13/";
        //Application Scope Url
        $scopeUrl     = "http://api.microsofttranslator.com";
        //Application grant type
        $grantType    = "client_credentials";

        //Create the AccessTokenAuthentication object.
        $authObj      = new AccessTokenAuthentication();
        //Get the Access token.
        $accessToken  = $authObj->getTokens($grantType, $scopeUrl, $clientID, $clientSecret, $authUrl);
        //Create the authorization Header string.
        $authHeader = "Authorization: Bearer ". $accessToken;

        //Set the params.//
        $fromLanguage = "en";
        $toLanguage   = "es";
        $inputStr     = $_POST["txtToTranslate"];
        $contentType  = 'text/plain';
        $category     = 'general';
    
        $params = "text=".urlencode($inputStr)."&to=".$toLanguage."&from=".$fromLanguage;
        $translateUrl = "http://api.microsofttranslator.com/v2/Http.svc/Translate?$params";
    
        //Create the Translator Object.
        $translatorObj = new HTTPTranslator();
    
        //Get the curlResponse.
        $curlResponse = $translatorObj->curlRequest($translateUrl, $authHeader);
    
        //Interprets a string of XML into an object.
        $xmlObj = simplexml_load_string($curlResponse);
        foreach((array)$xmlObj[0] as $val){
            $translatedStr = $val;
        }

    } catch (Exception $e) {
        echo "Exception: " . $e->getMessage() . PHP_EOL;
    }
}

?>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

The first thing this code does is to check to see if you are using POST to get to the page. If you browse to /translate.php">http://<server>/translate.php, you are issuing a GET command, so there’s no need to run the code. If the user has pushed the ‘Translate’ button, the form issues a POST command, and thus the code within the braces should run.

At the top, this code will include the helper classes you created earlier, and then it will use them to first get an access token from the Windows Azure Marketplace, and then use that to get a translation. If you look at the HTML for the form, you’ll see that the text box into which the user types the text to translate is called ‘txtToTranslate’, and PHP can get the contents of this from the postback using $_POST[‘txtToTranslate’], which it loads into a variable called $inputStr. The translation, when complete, will then be loaded into $translatedStr.

If you remember the HTML form that you created earlier, you echoed out these values, so now when you run the page, you’ll issue a GET and see the blank form. Type something into the text box and press the translate button, and you’ll issue a POST, which will run this code, translate the text, and then re-render the HTML form, echoing out the translated value. You have to echo out the input value too, or, the postback will just give you an empty textbox.

Here’s what it looks like:

image

Note where you have to put your client id and secret. Remember you saw how to sign up for the service and get them here.

Note also that the from language (‘en’) and to language (‘es’) are hard coded in this example. The codes for these languages, and all others supported by Microsoft Translator can be found here.

Happy Translating!

Skip to main content