Search code examples
phprsssimplexml

YouTube Feed has an object called @attributes how can I access it?


I am trying to get a YouTube RSS feed to work but I am struggling to get one of the attributes I need out of it. I have never seen part of the array starting with an @ sign so I think it may be some sort of a special element but I'm not sure. Code below and what I have already tried after.

Feed:

<?php
$xml->entry =
SimpleXMLElement::__set_state(array(
   'id' => 'yt:video:DjwM9SHJznM',
   'title' => 'JD19AT  - Joomla! in der Uni - Community-Arbeit als Lehrveranstaltung',
   'link' => 
  SimpleXMLElement::__set_state(array(
     '@attributes' => 
    array (
      'rel' => 'alternate',
      'href' => 'https://www.youtube.com/watch?v=DjwM9SHJznM',
    ),
  )),
   'author' => 
  SimpleXMLElement::__set_state(array(
     'name' => 'J and Beyond e.V.',
     'uri' => 'https://www.youtube.com/channel/UCy6ThiEDnalZOd_pgtpBk1Q',
  )),
   'published' => '2019-03-30T16:49:53+00:00',
   'updated' => '2019-05-09T16:56:18+00:00',
));
?>

Code:

$feed = $youtubeChannelFeed;
$xml = simplexml_load_file($feed);
$html = "";

This works $xml->entry->title;

but this doesn't $xml->entry->link it just says "SimpleXML Object"

As it says object I then tried using both -> arrow and ['attribute'] notation.

I tried escaping the @ with a \@ but that just caused an error.

How can I traverse the tree and get the value of to @attributes->href ?


Solution

  • The way I always try to remember this is that you can use an arrow or brackets to access data in an array or object.

    Array begins with A, but it chooses the one that's does not begin with A. Object is the one left over. That's how I remember it at least.

    In this case, although it was calling it a SimpleXMLObject it was actually showing me that it's an array in the print_r. So I had to use brackets to access like so:

    $xml->entry->link[0]['href']

    I couldn't work out how to access @attributes but I remember now that you don't need to know the name to access it, you can do it using number format too.

    If I'm honest I don't really know how I could access the first part with arrows as that appears to be an array too.