最近开发项目时遇到 php5.4 以前版本 json_encode 方法不支持 BIGINT 选项的问题,导致大整数 json 解码后变成科学计数法,现将解决方法整理如下:
<?php
header("Content-type: text/html; charset=utf-8");
/* 解决 json_decode 方法处理大整数时变成科学计数法的问题 */
echo "<pre>";
$json = <<<EOT
{
"foo" : "bar",
"small" : "123456",
"large" : 200000000000009093302
}
EOT;
print "原始Json数据:n$jsonn";
//正常解码
$result = json_decode ($json);
print "n正常解码的结果:n";
var_dump ($result);
if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
//如果PHP 5.4或更高版本,使用JSON "BIGINT" 选项
$result = json_decode ($json, false, 512, JSON_BIGINT_AS_STRING);
print "n使用BIGINT选项解码的结果(PHP 5.4+): n";
var_dump ($result);
} else {
//低版本的解决方法(大整数转换成字符串)
$json2 = fixJson ($json);
$result = json_decode ($json2);
print "nfixJson方法处理后的Json数据:n$json2n";
print "nfixJson方法处理后的数据解码结果: n";
var_dump ($result);
}
/* 将所有大整数增加引号转变为字符串 */
function fixJson ($json) {
return (preg_replace ('/:s?(d{14,})/', ': "${1}"', $json));
}