php json函数用法
今天使用POST方式(GET方式也要注意)向PHP提交了一个JSON数据,比如:
{"a":1,"b":2}
在PHP中取出这个数据:$s=$_POST['data'] ;//or $_GET['data'],然后这个串取出后是被转义的:{"a":1,"b":2}
如果直接调用:
$obj = json_decode( $s ); print_r( $obj ); echo $obj ->a;是错误的,会报告错误.如果$s直接定义:$s='{"a":1,"b":2}';则没有问题.所以在PHP中处理JSON时需要进行一下转义处理:$s=strips教程lashes($_POST['data']) ;这样再进行json解码就可以了.
json_decode — 对 JSON 格式的字符串进行编码
json_encode — 对变量进行 JSON 编码
Report a bug 说明
string json_encode ( mixed $value )
返回 value 值的 JSON 形式
Report a bug 参数
value
待编码的 value,除了resource 类型之外,可以为任何数据类型,该函数只能接受 UTF-8 编码的数据(译注:指字符/字符串类型的数据)
Report a bug 返回值
编码成功则返回一个以 JSON 形式表示的 string 。
Report a bug 范例
Example #1 A json_encode() 的例子,代码如下:
<?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}json_encode — 对变量进行 JSON 编码
json_decode — 对 JSON 格式的字符串进行编码
Report a bug 说明
mixed json_decode ( string $json [, bool $assoc ] )
接受一个 JSON 格式的字符串并且把它转换为 PHP 变量
Report a bug 参数
json
待解码的 json string 格式的字符串。
assoc
当该参数为 TRUE 时,将返回 array 而非 object 。
Report a bug 返回值
Returns an object or if the optional assoc parameter is TRUE, an associative array is instead returned.
Report a bug 范例
Example #1 json_decode() 的例子
<?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) } */查看更多关于php json函数用法 - php函数的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did30869