Reputation: 395
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.
Upvotes: 0
Views: 8972
Reputation: 1341
$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;
Upvotes: 1