json不轉義中文,不轉義斜線
阿新 • • 發佈:2018-12-30
1、顯示中文!
return json_encode(['code' => $code, 'message' => $message, 'data' => $data], JSON_UNESCAPED_UNICODE);
2、讓json字串好看一些!
return json_encode(['code' => $code, 'message' => $message, 'data' => $data], JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);
直接上測試程式碼:
<?php
$code = 220;
$message = '測試遊戲啊!';
$data = [1, 2, 3, 3, 4, 4, 7];
$test_data = ['code' => $code, 'message' => $message, 'data' => $data];
$test_0 = json_encode($test_data);
$test_1 = json_encode($test_data, JSON_UNESCAPED_UNICODE);
$test_2 = json_encode($test_data, JSON_PRETTY_PRINT);
$test_3 = json_encode($test_data , JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
echo "<pre>";
print_r($test_0);
echo '<hr>';
print_r($test_1);
echo '<hr>';
print_r($test_2);
echo '<hr>';
print_r($test_3);
echo "</pre>";
exit;
3、檢視測試結果:
4、json_encode不轉義斜線,不轉義中文:
return json_encode(['code' => $code, 'message' => $message, 'data' => $data], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
亦可寫作:
JSON_UNESCAPED_UNICODE + JSON_UNESCAPED_SLASHES = 320
json_encode($arr,320); #即可完成同時使用2個常量。但是不建議這樣寫,易讀性較差