简体   繁体   中英

How to translate a php string using google translate or any other translation service?

I need to translate a part of my wordpress site content using google translate, For example,

$text="translate this content"

to

$translated_text="traduci questo contenuto"

I do not need to find the browser language, etc,. Just direct translation I need. Tried this, seems like it is deprecated. Got it from another question answered here.

 function translate($from_lan, $to_lan, $text){
 $json = json_decode(file_get_contents('https://ajax.googleapis.com/ajax/services/language/translate? 
 v=1.0&q=' . urlencode($text) . '&langpair=' . $from_lan . '|' . $to_lan));
 $translated_text = $json->responseData->translatedText;
 return $translated_text;
 }

I don't mind paying for the google API, I need to know how to handle the translation in php code.

google translate currently posts a "application/x-www-form-urlencoded" with a f.req like

[[["AVdN8","[\"je voudrais bien te voir demain\",\"fr\",\"nl\"]",null,"generic"]]]

For an example in posting with PHP, see PHP post request

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM