Google 翻译 API - html 文档翻译

Google Translate API - html document translation

我正在尝试 Google 翻译 API 来翻译我的博客。访问 API 作品,我可以发送文本并获得适当的翻译,但每当我发送包含 HTML 的较大文档时,我再也不会从 API 得到任何答复。

我正在使用 PHP 通过下面的代码发送查询,我正在从我的 wordpress 网站中提取帖子(= 它只提取 body 标签之间的内容)。

PHP 代码:

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);
    }

如果我给变量提供:

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

我工作没有任何问题。

如果我用 html 输入 $text,我不会从 API 得到任何答案,甚至连错误信息都没有。我检查了文档并看到了这个:https://cloud.google.com/translate/markup

我尝试添加 body/header 部分,但它不起作用,但我希望我没有义务将其添加到我的代码中,因为这需要对所有页面进行重大更改才能实现工作。

你知道我怎样才能完成这项工作吗?

更新: 如果我在 PHP 中使用 substr 来减小 $text 的大小,我将它翻译成大约 5200 个字符,超过这个,我就什么也得不到了。

谢谢!

洛朗

文档建议发送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