简体   繁体   中英

Google Translate API - html document translation

I'm trying out Google Translate API to translate my blog. Access to the API works, I can send text and get the appropriate translation but whenever I send larger documents with HTML in it, I don't get any answer from the API anymore.

I'm using PHP to send the query with the code below and I'm extracting posts from my wordpress site (= it only extracts the content between the body tags).

PHP CODE:

function translation ($text,$origin,$destination)
    {
        $apiKey = 'MY_API_KEY';
        $url = 'https://www.googleapis.com/language/translate/v2?key='.$apiKey.'&q='.rawurlencode($text).&source='.$origin.'&target='.$destination;
        $handle = curl_init($url);
        curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($handle);                 
        $responseDecoded = json_decode($response, true);
        curl_close($handle);
        print_r($response);
        print_r($responseDecoded);
    }

If I feed the variables with:

$text: "hello world" 
$origin: "en"
$destination: "fr"

I works without any problem.

If I feed $text with html, I don't get any answer from the API, not even an error message. I checked the documentation and saw this: https://cloud.google.com/translate/markup

I tried to add the body/header part but it doesn't work but I hope I'm not obliged to add this into my code because this would require a major change on all the pages to make it work.

Do you have any idea of how I could make this work?

UPDATE: If I use substr in PHP to reduce the size of $text, I get it translated up to around 5200 chars, above this, I do not get anything any more.

Thanks!

Laurent

The documentation is recommending to send less than 5000 characters per request . In your case you would need to develop a function that splits the text into chunks of size less than 5000 characters (HTML tags included) and send them in separate requests. However, please be aware that there are also limits with respect to characters sent per 100 seconds and requests sent per 100 seconds .

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