扫码一下
查看教程更方便
本章节我们将为大家介绍如何使用 php 语言来编码和解码 json 对象。
在 php5.2.0 及以上版本已经内置 json 扩展。
函数 | 描述 |
---|---|
json_encode | 对变量进行 json 编码 |
json_decode | 对 json 格式的字符串进行解码,转换为 php 变量 |
json_last_error | 返回最后发生的错误 |
php json_encode() 用于对变量进行 json 编码,该函数如果执行成功返回 json 数据,否则返回 false 。
string json_encode ( $value [, $options = 0 ] )
参数
要注意的是 json_unescaped_unicode 选项,如果我们不希望中文被编码,可以添加该选项。
以下示例演示了如何将 php 数组转换为 json 格式数据:
1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
以上代码执行结果为:
{"a":1,"b":2,"c":3,"d":4,"e":5}
以下示例演示了如何将 php 对象转换为 json 格式数据:
name = "sachin";
$e->hobbies = "sports";
$e->birthdate = date('m/d/y h:i:s a', "8/5/1974 12:20:03 p");
$e->birthdate = date('m/d/y h:i:s a', strtotime("8/5/1974 12:20:03"));
echo json_encode($e);
?>
以上代码执行结果为:
{"name":"sachin","hobbies":"sports","birthdate":"08\/05\/1974 12:20:03 pm"}
使用 json_unescaped_unicode 选项
'迹忆客', 'taobao' => '淘宝网');
echo json_encode($arr); // 编码中文
echo php_eol; // 换行符
echo json_encode($arr, json_unescaped_unicode); // 不编码中文
?>
以上代码执行结果为:
{"jiyik":"\u8ff9\u5fc6\u5ba2","taobao":"\u6dd8\u5b9d\u7f51"}
{"jiyik":"迹忆客","taobao":"淘宝网"}
php json_decode() 函数用于对 json 格式的字符串进行解码,并转换为 php 变量。
mixed json_decode ($json_string [,$assoc = false [, $depth = 512 [, $options = 0 ]]])
参数
以下示例演示了如何解码 json 数据:
以上代码执行结果为:
object(stdclass)#1 (5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
array(5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}