慕容4345310
根据手册json_encode该方法可以返回一个非字符串(假的):返回JSON编码的字符串。FALSE在失败的时候。当这种情况发生时echo json_encode($data)将输出空字符串,该字符串为无效JSON.json_encode例如,会失败(并返回)false)如果它的参数包含一个非UTF-8字符串。应该在PHP中捕获此错误条件,例如:<?php
header("Content-Type: application/json");// Collect what you need in the $data variable.$json = json_encode($data);if ($json === false) {
// Avoid echo of empty string (which is invalid JSON), and
// JSONify the error message instead:
$json = json_encode(array("jsonError", json_last_error_msg()));
if ($json === false) {
// This should not happen, but we go all the way now:
$json = '{"jsonError": "unknown"}';
}
// Set HTTP response status code to: 500 - Internal Server Error
http_response_code(500);}echo $json;?>那么接收端当然应该意识到jsonError属性表示错误条件,应相应处理。在生产模式中,最好只向客户端发送通用错误状态,并记录更具体的错误消息,供以后研究。阅读有关处理JSON错误的更多信息PHP文档.