首页 > 解决方案 > How to prevent Google translate Api from converting "\n" , "\" and "/"

问题描述

I'm trying to translate strings from JSON throw PHP. This strings contains \n, \, / . After translation this character disapears or extra spaces will be added, it depends on the position of this chars.

Example:

red\ncars => voitures \ nrouges

red\n cars => voitures rouges

red/cars => rouge / voitures

...

I need to keep this chars like this

red\ncars => voiture\nrouge

red\n cars => voiture\n rouge

red/cars => rouge/voitures

...

$apiKey = 'xxx';
$source = 'en';
$target = 'fr'; 
$original_text = "voiture\nrouges";                 
$url = 'https://www.googleapis.com/language/translate/v2?key=' . $apiKey . '&q=' . rawurlencode($original_text) . '&source='.$source.'&target='.$target;
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($handle);                 
$responseDecoded = json_decode($response, true);
curl_close($handle);            
$translated_text = $responseDecoded['data']['translations'][0]['translatedText'];   
echo $translated_text ;

How can fix it ?

标签: phpgoogle-translate

解决方案


同样的问题\n是翻译后的\n。有人建议在请求中添加 "format" : "text" ,但没有帮助。当我解码 JSON 响应时,它由于 \ 而崩溃。

在我解码响应之前,我做了: translateText = translateText.replaceAll("\ n", "\n"); // 飞镖

嗯....恐慌解决方案已经使用了一段时间了


推荐阅读