PHP Google翻译API在一个POST请求中有多个文本字符串

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP Google翻译API在一个POST请求中有多个文本字符串相关的知识,希望对你有一定的参考价值。

根据googleSitepoint的说法,有可能在一个请求中翻译多个文本字符串。但是,当我尝试翻译多个字符串时,它导致用最后一个字符串替换第一个字符串。

    $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' => $heading, 'q' => $content, 'source' => $sl, 'target' => $hl));
curl_setopt($handle,CURLOPT_HTTPHEADER,array('X-HTTP-Method-Override: GET'));
$response = curl_exec($handle);
$responseDecoded = json_decode($response, true);
$responseCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
curl_close($handle);
if($responseCode != 200) {
    header("HTTP/1.0 404 Not Found");
    include_once("ErrorDocument/404.html");
    exit();
}else{
    $heading = $responseDecoded['data']['translations'][0]['translatedText'];
    $content = $responseDecoded['data']['translations'][1]['translatedText'];
}

有任何想法吗?

答案
    $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);
$data = array('key' => $apiKey,
                'q' => array($heading,$content),
                'source' => $sl,
                'target' => $hl);
curl_setopt($handle, CURLOPT_POSTFIELDS, preg_replace('/%5B(?:[0-9]|[1-9][0-9]+)%5D=/', '=', http_build_query($data)));
curl_setopt($handle,CURLOPT_HTTPHEADER,array('X-HTTP-Method-Override: GET'));
$response = curl_exec($handle);
$responseDecoded = json_decode($response, true);
$responseCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
curl_close($handle);
if($responseCode != 200) {
    header("HTTP/1.0 404 Not Found");
    include_once("ErrorDocument/404.html");
    echo 'Fetching translation failed! Server response code:' . $responseCode . '<br>';
    echo 'Error description: ' . $responseDecoded['error']['errors'][0]['message'] . '<br>';
    echo 'Please contact website administrator';
    exit();
}else{
    $heading = $responseDecoded['data']['translations'][0]['translatedText'];
    $content = $responseDecoded['data']['translations'][1]['translatedText'];
}

这对我很有用。找到解决方案out there。希望这将有助于未来的任何人。

另一答案

使用库GoogleTranslateForFree

“图书馆免费使用谷歌翻译。尝试连接故障和阵列支持。”

以上是关于PHP Google翻译API在一个POST请求中有多个文本字符串的主要内容,如果未能解决你的问题,请参考以下文章

使用纯 js 向 google api 发送 CORS POST 请求

从 AJAX 请求中去除 POST 的 PHP 配置?

Google Apps 脚本中的 POST 请求和 405 错误

用于通过PHP访问Youtube的Google API密钥

curl -F POST 请求翻译

谷歌翻译 API 的 Rest API 请求