Home > php教程 > php手册 > body text

json_decode返回错误代码4解决方法

WBOY
Release: 2016-06-06 20:11:04
Original
1421 people have browsed it

有可能是 PHP的版本不兼容 或者是 json的格式不正确 导致。 可以尝试使用如下代码: function jsonEncode($data) {if (2==func_num_args()) {$callee=__FUNCTION__;return json_format_scalar(strval(func_get_arg(1))).":".$callee($data);}is_object($data

有可能是PHP的版本不兼容或者是json的格式不正确导致。
可以尝试使用如下代码:

function jsonEncode($data) {
if (2==func_num_args()) {
$callee=__FUNCTION__;
return json_format_scalar(strval(func_get_arg(1))).":".$callee($data);
}
is_object($data) && $data=get_object_vars($data);
if (is_scalar($data)) { return json_format_scalar($data); }
if (emptyempty($data)) { return '[]';}
$keys=array_keys($data);
if (is_numeric(join('',$keys))) {
$data=array_map(__FUNCTION__,$data);
return '['.join(',',$data).']';
} else {
$data=array_map(__FUNCTION__,array_values($data),$keys);
return '{'.join(',',$data).'}';
}
}
function json_format_scalar($value) {
if (is_bool($value)) {
$value = $value?'true':'false';
} else if (is_int($value)) {
$value = (int)$value;
} else if (is_float($value)) {
$value = (float)$value;
} else if (is_string($value)) {
$value=addcslashes($value,"\n\r\"\/\\");
$value='"'.preg_replace_callback('|[^\x00-\x7F]+|','json_utf_slash_callback',$value).'"';
} else {
$value='null';
}
return $value;
}
function json_utf_slash_callback($data) {
if (is_array($data)) {
$chars=str_split(iconv("UTF-8","UCS-2",$data[0]),2);
$chars=array_map(__FUNCTION__,$chars);
return join("",$chars);
} else {
$char1=dechex(ord($data{0}));
$char2=dechex(ord($data{1}));
return sprintf("\u%02s%02s",$char1,$char2);
}
}
function json_utf_slash_strip($data) {
if (is_array($data)) {
return $data[1].iconv("UCS-2","UTF-8",chr(hexdec($data[2])).chr(hexdec($data[3])));
} else {
return preg_replace_callback('/(?','NULL')
,$data);
$data=preg_replace_callback('/#\d+/',__FUNCTION__,$data);
//抑制错误,诸如{123###}这样错误的JSON是不能转换成PHP数组的
@$data=eval("return $data;");
$strings=$count=0;
return $data;
} elseif (count($data)>1) {//存储字符串
$strings[]=json_utf_slash_strip(str_replace(array('$','\\/'),array('\\$','/'),$data[0]));
return '#'.($count++);
} else {//读取存储的值
$index=substr($data[0],1);
return $strings[$index];
}
}
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template