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...">

&lt;cfset var langPair = arguments.langFrom & "|" & arguments.langTo&gt;
&lt;cfset var theURL = "" & urlEncodedFormat(arguments.str) & "&langpair=" & urlEncodedFormat(langPair)&gt;
&lt;cfset var result = ""&gt;
&lt;cfset var data = ""&gt;

&lt;cfhttp url="#theURL#" result="result"&gt;

&lt;cfset data = deserializeJSON(result.fileContent)&gt;

&lt;cfif data.responseStatus neq 200&gt;
	&lt;cfreturn ""&gt;

&lt;cfreturn data.responseData.translatedText&gt;	

</cffunction> </code>

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.

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support.

Lafayette, LA