0

Here is my sample JSON:

[  
   {  
      "@attributes":{  
         "name":"Stack Overflow Movies ",
         "root":"http:\/\/www1.stackovermovies.com\/",
         "id":"1",
         "address":"Liverpool",
         "postcode":"PZ203434"
      },
      "films":{  
         "film":[  
            {  
               "@attributes":{  
                  "synopsis":"Description goes here.\r\n",
                  "poster":"http:\/\/www1.stackoverflowmovies.com\/posters\/HO00003702.jpg",
                  "cast":"Wayne Max",
                  "director":"",
                  "length":"125 mins",
                  "title":"X-Men (2016)",
                  "rating":"12A",
                  "release":"19\/11\/2016"
               },
               "shows":{  
                  "show":{  
                     "@attributes":{  
                        "date":"Sat 19 Nov",
                        "time":"17:00"
                     }
                  }
               }
        },

I tried to decode it:

The variable $feed contains the above JSON.

I tried to get the name attribute

echo $feed->'@attributes[0]'->name; but this is not working because of the @ character. Is there a workaround? I tried looking into CDATA but can't figure out if it's the right solution.

Vivek Singh
  • 2,453
  • 1
  • 14
  • 27
Cody Raspien
  • 1,753
  • 5
  • 26
  • 51

2 Answers2

3

Use json_decode($json, true) to get an array instead of an object. Then you can access your field like this:

$feed[0]['@attributes']['name'];
Bartosz Zasada
  • 3,762
  • 2
  • 19
  • 25
2

One way to access it is to provide a string value for the key in the object, like this:

$decoded->{'@attributes'};
Karl Laurentius Roos
  • 4,360
  • 1
  • 33
  • 42