2017-07-25 31 views
0

根據googleSitepoint,可能會在一個請求中翻譯多個文本字符串。但是,當我嘗試翻譯多個字符串時,它導致將第一個字符串替換爲最後一個字符串。一個POST請求中的PHP Google翻譯API多個文本字符串

$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']; 
} 

任何想法?

+0

你有多個鍵'q',第二個覆蓋第一個。 – pokeybit

+0

嘗試''q'=>數組($標題,$內容)' – pokeybit

+0

pokeybit - 我沒有在互聯網上找到這個解決方案,但我會嘗試。謝謝你的提示。編輯:不,只是給以下通知「注意:數組到字符串轉換」 –

回答

2
$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。希望這將有助於任何人在未來。

相關問題