您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

php json函数用法

2024/3/29 6:44:43发布16次查看
今天使用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) 

*/
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product