Google translator API using CURL post method

久未见 提交于 2019-12-22 13:12:49

问题


Did anyone have any experience in Google translator API v2 for translating HTML using PHP CURL on POST method?

I have tried several codes and libraries from github, but none of them worded for me. What I have found is GET methods.

Due to limitation for parsing data over GET or query string, I am unable to send large HTML data to translate.

I am looking for a solution/snippets which can translate buffered data using using CURL


回答1:


Here is my solution

$handle = curl_init();

if (FALSE === $handle)
   throw new Exception('failed to initialize');

curl_setopt($handle, CURLOPT_URL,'https://www.googleapis.com/language/translate/v2');
curl_setopt($handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($handle, CURLOPT_POSTFIELDS, array('key'=> 'apikey', 'q' => 'Testing message', 'source' => 'en', 'target' => 'cs'));
curl_setopt($handle,CURLOPT_HTTPHEADER,array('X-HTTP-Method-Override: GET'));
$response = curl_exec($handle);

You can also use POST to invoke the API if you want to send more data in a single request. The q parameter in the POST body must be less than 5K characters. To use POST, you must use the X-HTTP-Method-Override header to tell the Translate API to treat the request as a GET (use X-HTTP-Method-Override: GET).

Google Translate API Documentation



来源:https://stackoverflow.com/questions/30299652/google-translator-api-using-curl-post-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!