PHP群:95885625 Hbuilder+MUI群:81989597 站长QQ:634381967
    您现在的位置: 首页 > 开发编程 > PHP教程 > 正文

    php json函数json_decode用法

    作者:admin来源:网络浏览:时间:2020-09-30 00:07:50我要评论
    导读:今天使用POST方式(GET方式也要注意)向PHP提交了一个JSON数据,比如:{"a":1,"b":2}在PHP中取出这个数据:$s=$_POST['data'] ;//or $...
    今天使用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)
    }
    */ 

    转载请注明(B5教程网)原文链接:https://b5.mxunkeji.com/content-10-1362-1.html
    相关热词搜索: json_decode json函数