user3846091
user3846091

Reputation: 1703

Unable to decode json object using php?

I am trying to read a json object that is sent from a Rest Api call. However, i get a notice saying Undefined index. Is there anything i am missing ?

Notice: Undefined index subnet line 7

php

$response = file_get_contents('https://xyz:[email protected]/rest/v3/SoftLayer_Account/IpAddresses.json'); 

$data = json_decode($response,true);

echo "Gateway: ".$data["subnet"][0]["gateway"];
echo "NetMask: ".$data["subnet"][0]["netmask"];

echo "Done";
?>

IpAddresses.json

[
   {
      "id":12345,
      "subnet":{
         "netmask":"255.255.255.255",
         "gateway":"192.168.255.255"
      }
   },
   {
      "id":56789,
      "subnet":{
         "netmask":"255.255.255.255",
         "gateway":"192.168.255.255"
      }
   }
]

Upvotes: 0

Views: 87

Answers (1)

John Conde
John Conde

Reputation: 219804

You're close:

echo "Gateway: ".$data[0]["subnet"]["gateway"];
echo "NetMask: ".$data[0]["subnet"]["netmask"];

Write it like you read it: you want the first item's subnet netmask and gateway.

                                 ^      ^          ^ 
                                [0] ['subnet'] ['netmask']

Upvotes: 2

Related Questions