Translation via Google
Sorry for the lack of postings lately. Things are very busy at work lately so it will most likely be a quiet week. I did run into an interesting article via DZone today: Google Translation API: Translate on server side using PHP The author shows an example of hitting the Google Translation service with PHP. This is very unofficial as the service was meant for AJAX, but it does actually work via server side code. Anything written in PHP can be done in ColdFusion of course. Here is my version:
<cffunction name="translate" output="false" returnType="string">
<cfargument name="str" type="string" required="true" hint="Text to translate.">
<cfargument name="langfrom" type="string" required="true" hint="Language code of the original text.">
<cfargument name="langTo" type="string" required="true" hint="Language code to translate the text to...">
<cfset var langPair = arguments.langFrom & "|" & arguments.langTo>
<cfset var theURL = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=" & urlEncodedFormat(arguments.str) & "&langpair=" & urlEncodedFormat(langPair)>
<cfset var result = "">
<cfset var data = "">
<cfhttp url="#theURL#" result="result">
<cfset data = deserializeJSON(result.fileContent)>
<cfif data.responseStatus neq 200>
<cfreturn "">
</cfif>
<cfreturn data.responseData.translatedText>
</cffunction>
To call it, you just supply the string and the language from and to arguments:
<cfoutput>#translate("Pardon me, but do you have any expensive, pretentious yellow mustard?", "en", "fr")#</cfoutput>
This returns:
Excusez-moi, mais avez-vous cher, prétentieux jaune moutarde?
I don't know French, but that certainly looks right to me. Again, as this is unofficial, I wouldn't expect it to always work, and for this reason I won't submit the code to CFLib. Hopefully though it will be use to someone.
Comments
Your text above results in:
"????????, ???? ????? ??????????? ??????, ?????????? ??????? ?????????;"
which is understandable but not quite there - same problem.
I do use Google Translate almost everyday at work (not via the API), and it does help. I'm translating articles so I can write a brief summary in English - Google Translate, Babelfish, etc. generally get enough words right that I'm able to use their translations.
It prevents having to add the google source script on the page you want to use the translation feature. And if you want the Ajax it.. you can always call the function with jQuery
Thanks Ray
I will extend it to support more document type and eventually do live translation.
PS : Can add me to the coldfusionbloggers feed too ? :-)


Excusez moi, mais avez vous de la moutarde chère prétentieuse et jaune?