0

I am trying for get one field value from json response but I am unable to get it. My PHP code is like below

$servers    = $sp->server_list();
print_r ($servers);

Its giving me result like below

stdClass Object ( [data] => Array ( [0] => stdClass Object ( [id] => S9rr4Un0SYlPGR6E [name] => localhost [autoupdates] => 1 [firewall] => [deny_unknown_domains] => [lastconn] => 1544645254 [lastaddress] => 50.116.20.23 [datecreated] => 1511884238 [plan] => grandfathered_coach [available_runtimes] => Array ( [0] => php5.4 [1] => php5.5 [2] => php5.6 [3] => php7.0 [4] => php7.1 [5] => php7.2 [6] => php7.3 ) ) ) ) 

I want get value called id from it and want use it in my php. I have tried json decode method like below

$decoded_data = json_decode($servers,TRUE); 
$myid = $decoded_data['data']['id'];

its giving me error like below

Warning: json_decode() expects parameter 1 to be string, object given in C:\xampp\htdocs\code\new2.php on line 11

I have searched many questions and answer here but I am unable to get it resolved. Let me know if someone can help me. Thanks a lot.

2
  • There may be a JSON response at some point, but if so, something in the server_list() method has already decoded it for you. Commented Dec 12, 2018 at 20:36
  • @Don'tPanic I have got solved using answer but I am getting error called Fatal error: Uncaught Error: Cannot use object of type stdClass as array in when I use it with $systemUser = $sp->sysuser_create($server_id, $system_user, $system_user_password); Let me know if you can help me for it Commented Dec 12, 2018 at 21:20

1 Answer 1

1

$servers is an object with key data which is an array. You can access the first element in the array using index 0 then you can get the id.

Json decode is not needed as $servers is already an object. You use json decode to go from json string to object. You can learn more about PHP JSON decode

$servers = $sp->server_list();
echo $myId = $servers->data[0]->id;
Sign up to request clarification or add additional context in comments.

8 Comments

its giving me error like Warning: json_decode() expects parameter 1 to be string, object given in C:\xampp\htdocs\code\new2.php on line 11
this error in $decoded_data = json_decode($servers,TRUE); this line
You dont need to use json decode. As servers in not a json string. It is an object.
@AbraCadaver what if its array casted. Do u know if the nested object will need to be array casted separately. Either way i have removed it as an alternative.
You would have to cast both (array)$servers; and (array)$servers['data'][0]->id;
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.