本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

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

发布于2023-05-25 21:38     阅读(500)     评论(0)     点赞(14)     收藏(4)


I want to get data from API but instead keep getting 'Undefined Property' PHP error.

I am trying to get 'SESSION_ID' in Datas in Data. (JSON/POST)

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

And my PHP code to retrieve SESSION_ID is like this. First, sending $data and get the 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;
}

As I am PHP beginner, I am not sure whether that one error line is the problem, or the whole structure is wrong. Please help!


解决方案


if your return from the $result is really like the json you wrote, your code is working,

i think you need to print_r($result) from the curl;

this code might help:

<?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;


所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:http://www.phpheidong.com/blog/article/546158/d5e22f7610fea543abe6/

来源:php黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

14 0
收藏该文
已收藏

评论内容:(最多支持255个字符)