简体   繁体   中英

Google translator API using CURL post method

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

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

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