正在 PHP 中检索 JSON 数据(有 'Undefined Property' 错误)

Retrieving JSON data in PHP (having 'Undefined Property' error)

我想从 API 获取数据,但一直收到 'Undefined Property' PHP 错误。

我正在尝试在 Datas in Data 中获取 'SESSION_ID'。 (JSON/POST)

{
"Data":
{
    "Code":"00",
    "Datas":
    {
        "COM_CODE":"80001",
        "USER_ID":"USER_ID",
        "SESSION_ID":"39313231367c256562253866253939256563253838253938:0HDD9DBtZt2e"
    },
    "Message":"",
    "RedirectUrl":""
},
"Status":"200",
"Error":null 
}

我的 PHP 检索 SESSION_ID 的代码是这样的。首先,发送 $data 并获得 SESSION_ID.

function api_login(){


$data = array(
    "COM_CODE" => "000000",
    "USER_ID" => "USER"
    );

$ch = curl_init( "https://apifakeurl.com/Login" );
$payload = json_encode($data);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $payload );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);

$json = json_decode($result);

$session_id = $json->Data->Datas->SESSION_ID;
//Here is the line where I get the 'Undefined Property' error.

return $session_id;
}

由于我是PHP初学者,我不确定是那一行出错了,还是整个结构有问题。请帮忙!

我很幸运地使用了这个语法: $session_id = $json['Data']['Datas']['SESSION_ID'];

如果括号内没有单引号,则无效。

如果 $result 中的 return 与您编写的 json 非常相似,那么您的代码可以正常工作,

我认为你需要 print_r($result) 卷曲;

此代码可能有帮助:

<?php


$json = '{
"Data":
{
    "Code":"00",
    "Datas":
    {
        "COM_CODE":"80001",
        "USER_ID":"USER_ID",
        "SESSION_ID":"39313231367c256562253866253939256563253838253938:0HDD9DBtZt2e"
    },
    "Message":"",
    "RedirectUrl":""
},
"Status":"200",
"Error":null 
}';

echo '<pre>';
$decode = json_decode($json);
print_r(json_decode($json));
$session_id = $decode->Data->Datas->SESSION_ID;
echo $session_id;