本教程操作环境:windows7系统、php7.1版,dell g3电脑
php json常用方法:
1、json_encode()
php json_encode() 用于对变量进行 json 编码,该函数如果执行成功返回 json 数据,否则返回 false 。
语法
string json_encode ( $value [, $options = 0 ] )
示例:
<?php $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5); echo json_encode($arr);?>
输出结果:
{"a":1,"b":2,"c":3,"d":4,"e":5}
2、json_encode()
json_decode() 函数用于对 json 格式的字符串进行解码,并转换为 php 变量。
语法:
mixed json_decode ($json_string [,$assoc = false [, $depth = 512 [, $options = 0 ]]])
参数:
json_string: 待解码的 json 字符串,必须是 utf-8 编码数据
assoc: 当该参数为 true 时,将返回数组,false 时返回对象。
depth: 整数类型的参数,它指定递归深度
options: 二进制掩码,目前只支持 json_bigint_as_string 。
示例:
<?php $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; var_dump(json_decode($json)); var_dump(json_decode($json, true));?>
输出结果:
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)}
3、json_last_error()
json_last_error — 返回最后发生的错误
语法:
json_last_error()
如果有,返回 json 编码解码时最后发生的错误。会返回一个整型(integer),这个值会是以下的常量之一:
json 错误码常量含义可用性
json_error_none 没有错误发生
json_error_depth 到达了最大堆栈深度
json_error_state_mismatch 无效或异常的 json
json_error_ctrl_char 控制字符错误,可能是编码不对
json_error_syntax 语法错误
json_error_utf8 异常的 utf-8 字符,也许是因为不正确的编码。 php 5.3.3
json_error_recursion one or more recursive references in the value to be encoded php 5.5.0
json_error_inf_or_nan one or more nan or inf values in the value to be encoded php 5.5.0
json_error_unsupported_type 指定的类型,值无法编码。 php 5.5.0
json_error_invalid_property_name 指定的属性名无法编码。 php 7.0.0
json_error_utf16 畸形的 utf-16 字符,可能因为字符编码不正确。 php 7.0.0
示例:
<?php// 一个有效的 json 字符串$json[] = '{"organization": "php documentation team"}';// 一个无效的 json 字符串会导致一个语法错误,在这个例子里我们使用 ' 代替了 " 作为引号$json[] = "{'organization': 'php documentation team'}";foreach ($json as $string) { echo 'decoding: ' . $string; json_decode($string); switch (json_last_error()) { case json_error_none: echo ' - no errors'; break; case json_error_depth: echo ' - maximum stack depth exceeded'; break; case json_error_state_mismatch: echo ' - underflow or the modes mismatch'; break; case json_error_ctrl_char: echo ' - unexpected control character found'; break; case json_error_syntax: echo ' - syntax error, malformed json'; break; case json_error_utf8: echo ' - malformed utf-8 characters, possibly incorrectly encoded'; break; default: echo ' - unknown error'; break; } echo php_eol;}?>
输出结果:
decoding: {"organization": "php documentation team"} - no errorsdecoding: {'organization': 'php documentation team'} - syntax error, malformed json
推荐学习:《php视频教程》
以上就是php json常用方法有哪些的详细内容。
