为什么json_decode不起作用?

时间:2017-12-14 03:11:49

标签: php json

我试图从下面的代码中通过JSON获取c_user, xs, frdate值的值,并将其保存到数据库,但它不能用于我使用的代码。

$data = $_GET["user"];
$data = json_decode($data);
$datr = $data->datr;
$xs = $data->xs;
$fr = $data->fr;
$c_user = $data->c_user;
$token2 = $data->access_token;
$id = $data->uid;

这是Json代码

{
    "session_key" : "5.rWdMmED7nybZ1w.1513220229.45-100007001746590",
    "uid" : 100007001746590,
    "secret" : "b3f2dac4a948407864ff2e4e2d8feebf",
    "access_token" : "EAAAAAYsX7TsBAGSNv9YET43NxPk7PZBt1gTP0ipqQpb7ojzgn9pFf8hOLTg6V1R8IAv0y5TYgMhDlbCA0eHUN5aPOYw1DgA4c7vTgscbzY0tZALxpBk1tvIXPAisZBBZBzkyimkBurkU3iz0KmXoLQU1KY7tjxrgl7Wvxf5GwZBQbDFX4m5kMsYYDZB9UwIyl6YJA12Ac2ZBmcQBKAfOotc",
    "machine_id" : "hegxWhFD-5BKWnhTe3exWvAG",
    "session_cookies" : [
        {
            "name" : "c_user",
            "value" : "100007001746590",
            "expires" : "Fri,
             14 Dec 2018 02 : 57 : 09 GMT",
             "expires_timestamp" : 1544756229,
            "domain" : ".facebook.com",
            "path" : "\/",
            "secure" : true
        },
        {
            "name" : "xs",
            "value" : "45 : rWdMmED7nybZ1w : 2 : 1513220229 : 13473 : 4832",
            "expires" : "Fri,
             14 Dec 2018 02 : 57 : 09 GMT",
             "expires_timestamp" : 1544756229,
            "domain" : ".facebook.com",
            "path" : "\/",
            "secure" : true,
            "httponly" : true
        },
        {
            "name" : "fr",
            "value" : "0DfY4nJ3NUUeFKIUG.AWX4RKAQ0wBcl677F8jXJcCZ7Dc.BZj9JZ.fD.Fox.0.0.BaMeiF.AWXzlwrU",
            "expires" : "Fri,
             14 Dec 2018 02 : 57 : 09 GMT",
             "expires_timestamp" : 1544756229,
            "domain" : ".facebook.com",
            "path" : "\/",
            "secure" : true,
            "httponly" : true
        },
        {
            "name" : "datr",
            "value" : "hegxWhFD-5BKWnhTe3exWvAG",
            "expires" : "Sat,
             14 Dec 2019 02 : 57 : 09 GMT",
             "expires_timestamp" : 1576292229,
            "domain" : ".facebook.com",
            "path" : "\/",
            "secure" : true,
            "httponly" : true
        }
    ],
    "confirmed" : true,
    "identifier" : "7250492401"
}

注意:我成功获得$token2$id。如何获取xs, fr, date, c_user

的值

3 个答案:

答案 0 :(得分:1)

对于所有丢失的密钥,错误似乎都是一致的。以xs为例。您编写的代码会查找标记为xs的子元素:

$xs = $data->xs;

但是这并不存在于您的JSON文档中。相反,您需要解析session_cookies数组以查找name键设置为xs的元素。此方法在此previous answer中进行了描述。

答案 1 :(得分:0)

哦,我明白了。您询问的值是JSON 数组的元素,其中“name”值类似于“xs”和“fr”。您需要遍历数组才能解压缩。

$cookies = [];
foreach ($data->session_cookies as $cookie) {
    $cookies[$cookie->name] = $cookie->value;
}
$xs = $cookies['xs'];
// etc.

答案 2 :(得分:0)

大概这就是你要找的东西。我想。

$data = $_GET["user"];
$data = json_decode($data);
$c_user = [];
foreach($data->session_cookies as $key => $val)
{
    $c_user[] = $val['name']; 
}

现在在c_user数组中,您拥有所需的值。