PHP中JSON处理
json_encode
json_encode 目前只能处理UTF-8编码的数据
JSON_UNESCAPED_UNICODE 让JSON更懂中文
解析出错,看 json_last_error() 返回的错误
JSON格式是灵活开放的,特殊情况可以用sprintf来自己组装或者解析JSON字符串
语法:
string json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] )
参数:
JSON_HEX_TAG 所有的 < 和 > 转换成 \u003C 和 \u003E
JSON_HEX_AMP 所有的 & 转换成 \u0026
JSON_HEX_APOS 所有的 ' 转换成 \u0027
JSON_HEX_QUOT 所有的 " 转换成 \u0022
JSON_FORCE_OBJECT 强制使用索引数组输出
JSON_NUMERIC_CHECK 将所有数字字符串编码成数字
JSON_BIGINT_AS_STRING 将大数字编码成原始字符原来的值
JSON_PRETTY_PRINT 用空白字符格式化返回的数据
JSON_UNESCAPED_SLASHES 不要编码 /
JSON_UNESCAPED_UNICODE 以字面编码多字节 Unicode 字符(默认是编码成 \uXXXX)
示例
JSON_PRETTY_PRINT ,有的时候需要查看,所以中格式化的效果更美观
$arr = array('a' => 'b' , 'b' => 'c');
echo json_encode($arr, JSON_PRETTY_PRINT);
echo "\n";
echo json_encode($arr);
结果:
{
"a": "b",
"b": "c"
}
{"a":"b","b":"c"}
json_encode($b, JSON_FORCE_OBJECT) 可以强制转换成对象
json_decode
json_decode($res, true);
拼装json
简单示例:
$format = '["%s",%d,%b]';
$jsonstr= sprintf($format, '张三', 15 , false );
echo $jsonstr;
echo "\n";
$json=json_decode($jsonstr);
echo "\n";
print_r($json);
echo json_last_error_msg();
结果:
["张三丰",16,0]
Array
(
[0] => 张三丰
[1] => 16
[2] => 0
)
No errorr
封装函数:
$arr = ['北京'=>['a',123=>[] ],'热门'];
$arr = array('a' => 'b');
echo encode($arr);
function encode($data) {
switch ($type = gettype($data)) {
case 'NULL':
return 'null';
case 'boolean':
return ($data ? 'true' : 'false');
case 'integer':
case 'double':
case 'float':
return $data;
case 'string':
return '"' . addcslashes($data, "\r\n\t\"") . '"';
case 'object':
$data = get_object_vars($data);
case 'array':
$count = 0;
$indexed = array();
$associative = array();
foreach ($data as $key => $value) {
if($count !== NULL && (gettype($key) !== 'integer' || $count++ !== $key)) {
$count = NULL;
}
$one = encode($value);
$indexed[] = $one;
$associative[] = encode($key) . ':' . $one;
}
if ($count !== NULL) {
return '[' . implode(',', $indexed) . ']';
} else {
return '{' . implode(',', $associative) . '}';
}
default:
return ''; // Not supported
}
}
Last updated
Was this helpful?