Friday Free Code – Auto Google Translate (php)
Below you will find a handy dandy piece of code that The Kaptain uses to take some content and make it just a little bit more unique.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | function googletranslate( $text, $destLang = 'es', $srcLang = 'en' ) { $text = substr($text,0,1500); $text = urlencode( $text ); $destLang = urlencode( $destLang ); $srcLang = urlencode( $srcLang ); $url = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=$text&langpair=$srcLang|$destLang"; $trans = wpbf_http_get( $url ); $json = json_decode( $trans, true ); if( $json['responseStatus'] != '200' ) { return false; }else{ return $json['responseData']['translatedText']; } } |
Now, the way I generally use this is to have the script randomly select a couple languages from the list then loop the content through each one. See below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | $mytext = "Some big block of text up to 1500 characters long"; $langs = array("es","fr","de","it","nl","ru"); //add any other language supported by Google Translate or remove ones you don't want to use $i = 1; $useLangs = array(); //you can change the 3 to whichever number you want to have your text translated more or less times while($i < 3){ $z = $langs[array_rand($langs)]; if(!in_array($z,$useLangs)){ $useLangs[] = $z; $i++; } } $useLangs[] = "en"; //whatever language you want the content to end up in $lastLang = "en"; //whatever language your content is in originally foreach($useLangs as $lang){ $mytext= googletranslate($mytext,$lang,$lastLang); $lastLang = $lang; } //echo out your newly translated text! echo $mytext; |

Leave a Reply
You must be logged in to post a comment.