json_encode返回null解决方法
时间:2019-11-20 08:52:02 来源:igfitidea点击:
json_encode返回null
json_last_error 返回5
诊断过程
json_encode()时返回null。
这时,可以使用json_last_error检查报错的原因。
根据json_last_error_msg信息
JSON_ERROR_NONE => 'No error', 没有错误
JSON_ERROR_DEPTH => 'Maximum stack depth exceeded', json_encode错误 超过最大堆栈深度
JSON_ERROR_STATE_MISMATCH => 'State mismatch (invalid or malformed JSON)', json_encode错误 状态不匹配(JSON无效或格式错误)
JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded', json_encode错误 控制字符错误,可能编码错误
JSON_ERROR_SYNTAX => 'Syntax error', json_encode错误,语法错误
JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded' JSON报错,错误代码5 UTF-8字符格式错误,可能编码错误
返回代码5表示 Malformed UTF-8 characters, possibly incorrectly encoded UTF-8字符格式错误,可能编码错误
解决方案
将字符串转换成UTF-8
方法1
$string = mb_convert_encoding($string, 'UTF-8', 'UTF-8'); $res = json_encode(['theitroad'=> $string]);
方法2
function utf8ize( $mixed ) {
if (is_array($mixed)) {
foreach ($mixed as $key => $value) {
$mixed[$key] = utf8ize($value);
}
} elseif (is_string($mixed)) {
return mb_convert_encoding($mixed, "UTF-8", "UTF-8");
}
return $mixed;
}
$string = json_encode( utf8ize( $string ) );

