1

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!

Dahn Hwang
  • 45
  • 8
  • 1
    `echo $result` and see if it's the same JSON as you posted. If it is exactly the same, you should not be getting an "Undefined Property" error message. – Amal Murali May 29 '17 at 06:04
  • You should be checking that $result != false before using the data as it's also possible that this part can fail for all sorts of reasons. – Nigel Ren May 29 '17 at 06:22
  • @AmalMurali Thanks for your help. `$result` was the problem. – Dahn Hwang May 31 '17 at 07:17
  • @NigelRen I checked the `$result` and now it is working. Thanks for taking your time! :) – Dahn Hwang May 31 '17 at 07:18

2 Answers2

0

I had luck with this syntax: $session_id = $json['Data']['Datas']['SESSION_ID'];

Didn't work without single quotes inside brackets.

Bman70
  • 743
  • 5
  • 11
  • The `SESSSION_ID` I wanted to get was formatted in array not in object. Thanks for taking your time anyway. – Dahn Hwang May 31 '17 at 07:21
0

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;
Josua Marcel C
  • 3,122
  • 6
  • 45
  • 87