Search code examples
phpjsonrestresponsevtiger

How to get access the properties in this json response?


I am executing a curl request and get a response which returns a json response. Below is the code after the response is sent back.

Response: "Zeros Replaced real token"

{"success":true,"result":{"token":"000000000","serverTime":1471365111,"expireTime":1471365411}}1

Code Used (For Testing) and accessing property: $json = json_decode($result); print_r($json); // Prints the Json Response

$firsttry = $json->result['token']; //Access Property results in error :Trying to get property of non-object
$secondtry = $json['token']; 

echo $firsttry.'<br>';//Code can't continue because of error from $firsttry.
print_r( $secondtry.'<br>');//Nothing Prints at all

I did notice a weird anomaly where it prints a 1 at the end, where as if i do

json_encode($json);

The return response replaces the one at the end of the string with a "true" Could the "1 or true" at the end be throwing of the json decode?

Maybe I am missing something simple?

As Requested full test code

$url = "https://website.com/restapi.php";
//username of the user who is to logged in. 
$userName="adminuser"; //not real user

$fields_string; //global var


$fields = array( //array will have more in the future
'username' => urlencode($userName)
 );

//url-ify the data for the POST
foreach($fields as $key=>$value) { global $fields_string;
$fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,         $url.'?'.$fields_string.'operation=getchallenge');
curl_setopt($ch,CURLOPT_POST, count($fields));

//execute post
$result = curl_exec($ch);

//close connection
curl_close($ch);

Solution

  • json_decode(), by default makes child objects into stdClass objects rather than arrays unless they are explicitly arrays.

    Try something like:

    $firsttry = $json->result->token;