Home >Backend Development >PHP Tutorial >JSON versions below php5.4 do not support Chinese solutions without escaping content_PHP Tutorial
This article mainly introduces the solution that json in versions below php5.4 does not support unescaped content in Chinese The solution is to simulate joson Chinese without escaping through a custom php method, which has certain reference value. Friends in need can refer to it
The example in this article describes the solution to the problem that json in versions below php5.4 does not support unescaped Chinese content. Share it with everyone for your reference. The specific analysis is as follows:
When writing the ERP interface, I encountered the JAVA side receiving this json_encoded content
The code is as follows:
I checked the PHP manual and found that those below 5.4 must escape Chinese, but the PHP version on our server is 5.3, so we used PHP to simulate a JSON method.
The code is as follows:
if ($var === true)
return 'true';
if ($var === false)
return 'false';
static $reps = array(
array("\", "/", "n", "t", "r", "b", "f", '"', ),
array('\\', '\/', '\n', '\t', '\r', '\b', '\f', '"', ),
);
if (is_scalar($var))
return '"' . str_replace($reps[0], $reps[1], (string) $var) . '"';
if (!is_array($var))
throw new Exception('JSON encoder error!');
$isMap = false;
$i = 0;
foreach (array_keys($var) as $k) {
if (!is_int($k) || $i != $k) {
$isMap = true;
break;
}
}
$s = array();
if ($isMap) {
foreach ($var as $k => $v)
$s[] = '"' . $k . '":' . call_user_func(__FUNCTION__, $v);
return '{' . implode(',', $s) . '}';
} else {
foreach ($var as $v)
$s[] = call_user_func(__FUNCTION__, $v);
return '[' . implode(',', $s) . ']';
}
}
}
When using it, just use it directly as a built-in function. json_encode_ex(array('Diaoyu Island'=>'China')); also supports multi-dimensional arrays.
I hope this article will be helpful to everyone’s PHP programming design.