如何让Google Cloud Translate PHP API返回实际字符而非Unicode转义序列
问题:Cloud Translate PHP SDK返回Unicode转义字符而非实际字符
使用Cloud Translate PHP SDK翻译JSON文件中的字符串时,返回的翻译结果是Unicode转义字符而非实际字符,比如:
"Exp\u00e9riences"
每次都要逐个搜索替换,非常麻烦,有没有办法让API返回实际字符而非这种Unicode转义序列?
我的实现代码
public function translateJsonFile(Request $request) { $htmlString = ''; $source = 'en'; $target = 'it'; $key = 'My key'; $translate = new TranslateClient([ 'key' => $key ]); $newArray = []; $json = File::get(base_path() . '/resources/lang/english.json'); $array = json_decode($json, true); foreach ($array as $key => $value) { $text_translated = $translate->translate($value, [ 'source' => $source, 'target' => $target ])['text']; $newArray[$key] = $text_translated; usleep( 500000 ); } $fileName = '/temp/translated-'.rand(1,1000).'.json'; Storage::disk('public')->put($fileName, json_encode($newArray)); return response()->json([ 'newArray' => $newArray, ]); }
解决方法
问题不在Cloud Translate API本身,而是json_encode()的默认行为导致的——PHP的json_encode()默认会将非ASCII字符转为Unicode转义序列。
你只需要在调用json_encode()时添加JSON_UNESCAPED_UNICODE参数,就能让它输出实际的Unicode字符而非转义序列:
修改后的关键代码
- 保存JSON文件时:
Storage::disk('public')->put($fileName, json_encode($newArray, JSON_UNESCAPED_UNICODE));
- 返回响应时:
return response()->json([ 'newArray' => $newArray, ], 200, [], JSON_UNESCAPED_UNICODE);
完整修改后的函数
public function translateJsonFile(Request $request) { $htmlString = ''; $source = 'en'; $target = 'it'; $key = 'My key'; $translate = new TranslateClient([ 'key' => $key ]); $newArray = []; $json = File::get(base_path() . '/resources/lang/english.json'); $array = json_decode($json, true); foreach ($array as $key => $value) { $text_translated = $translate->translate($value, [ 'source' => $source, 'target' => $target ])['text']; $newArray[$key] = $text_translated; usleep( 500000 ); } $fileName = '/temp/translated-'.rand(1,1000).'.json'; // 添加参数避免Unicode转义 Storage::disk('public')->put($fileName, json_encode($newArray, JSON_UNESCAPED_UNICODE)); // 返回响应时同样添加参数 return response()->json([ 'newArray' => $newArray, ], 200, [], JSON_UNESCAPED_UNICODE); }
修改后,生成的JSON文件和返回的响应里会直接显示"Expériences"这类实际字符,不再出现Unicode转义序列。
内容的提问来源于stack exchange,提问作者gabogabans
相关产品推荐
相关产品推荐

