22
03月
21
数组里面有其他语种导致json_encode报错的处理
其实官方文档有给解决方案,但是没有解决好,下面是我实测没问题的代码!
/**
* 描述 : json_encode格式化
* 参数 :$value 需要encode的数据
* 作者 : Smart.Chen
*/
public function safe_json_encode($value, $options = 0, $depth = 512, $utfErrorFlag = false) {
$encoded = json_encode($value, $options, $depth);
switch (json_last_error()) {
case JSON_ERROR_NONE:
return $encoded;
case JSON_ERROR_DEPTH:
return 'Maximum stack depth exceeded'; // or trigger_error() or throw new Exception()
case JSON_ERROR_STATE_MISMATCH:
return 'Underflow or the modes mismatch'; // or trigger_error() or throw new Exception()
case JSON_ERROR_CTRL_CHAR:
return 'Unexpected control character found';
case JSON_ERROR_SYNTAX:
return 'Syntax error, malformed JSON'; // or trigger_error() or throw new Exception()
case JSON_ERROR_UTF8:
$clean = self::utf8ize($value);
if ($utfErrorFlag) {
return 'UTF8 encoding error'; // or trigger_error() or throw new Exception()
}
return self::safe_json_encode($clean, $options, $depth, true);
default:
return 'Unknown error'; // or trigger_error() or throw new Exception()
}
}
/**
* 描述 : 转utf-8
* 作者 : Smart.Chen
*/
public function utf8ize($mixed) {
if (is_array($mixed)) {
foreach ($mixed as $key => $value) {
$mixed[$key] = self::utf8ize($value);
}
} else if (is_string ($mixed)) {
//这里和官方文档有区别
return mb_convert_encoding($mixed,'UTF-8','UTF-8');
}
return $mixed;
}
非特殊说明,本文版权归 Smart.Chen个人博客 所有,转载请注明出处.
本文标题: php json_encode错误处理