Status
Not open for further replies.
5 comments
no i dont need something to translate my site, but i need a script with bing translate api to translate words and sentence. just like a dictionary.
 
PHP:
<?php
class Translator {
    // TRUE to enable print_r etc later on
    private $debugging = false;
    
	public function Translate($source_lang = "", $source = "Hello", $dest_lang = "et") {
        // We generate some headers for the file_get_contents() function to make the request look more legit
        $headers = stream_context_create(array("http" => array("method" => "GET", "header" => "Accept-Charset: utf-8;q=0.7,*;q=0.3\r\nUser-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.63 Safari/535.7\r\nAccept: */*\r\nReferer: http://www.microsofttranslator.com/")));
        // We use a regular expression to extract the translated part from the response
		preg_match('!TranslatedText":"(.+?)","Tra!', file_get_contents("http://api.microsofttranslator.com/v2/ajax.svc/TranslateArray?appId=%22TNDJ9zfD_HXiAgFDKfCLz8fg92HEHFGOb93cdM6nxohI*%22&texts=[%22".urlencode($source)."%22]&from=%22".$source_lang."%22&to=%22".$dest_lang."%22&oncomplete=_mstc1&onerror=_mste1&loc=en&ctr=England&rgp=d18478d", null, $headers), $translated);
        // In case we ever need to debug
        if($this->debugging)print_r($translated);
        // If the regular expression works like a charm, then return the translation, otherwise return false
        return (!empty($translated[1])) ? $translated[1] : false;
	}
	
}
// We use UTF-8 to avoid problems with tricky letters
header("Content-type: text/html; charset=utf-8");
// We initialise a new class
$translator = new Translator;
// We run the function that takes 3 arguments at most (leave the first one empty to use automatic detection)
echo $translator->Translate("", "Hey there, how are you?", "es");
 
Status
Not open for further replies.
Back
Top