22

I'm trying to get the video data from this youtube playlist feed and add the interesting data to an array and use that later, but as you can see from the feed some videolinks are "dead" and that results in problems for my code.

The error I get is "Node no longer exists" when I try to access $attrs['url']. I've tried for hours to find a way to check if the node exists before I access it but I have no luck.

If anyone could help me to either parse the feed some other way with the same result or create a if-node-exists check that works I would be most happy. Thank you in advance

$url = 'http://gdata.youtube.com/feeds/api/playlists/18A7E36C33EF4B5D?v=2';

$sxml = simplexml_load_file($url);
$i = 0;
$videoobj;

foreach ($sxml->entry as $entry) {
    // get nodes in media: namespace for media information
    $media = $entry->children('http://search.yahoo.com/mrss/');

    // get video player URL
    $attrs = $media->group->player->attributes();
    $videoobj[$i]['url'] = $attrs['url'];

    // get video thumbnail
    $attrs = $media->group->thumbnail[0]->attributes();
    $videoobj[$i]['thumb'] = $attrs['url']; 
    $videoobj[$i]['title'] = $media->group->title;
    $i++;
}
Andreas Norman
  • 323
  • 1
  • 2
  • 5

2 Answers2

24
if ($media->group->thumbnail && $media->group->thumbnail[0]->attributes()) {
    $attrs = $media->group->thumbnail[0]->attributes();
    $videoobj[$i]['thumb'] = strval($attrs['url']);
    $videoobj[$i]['title'] = strval($media->group->title);
}
Björn
  • 29,019
  • 9
  • 65
  • 81
  • 8
    Let me suggest an issue, try to explain a little about the problem. This helps a lot. – Vítor Oliveira Aug 02 '16 at 21:33
  • 3
    Important thing - check `$media->group->thumbnail[0]` - you need check this xml object for empty. If it is true then on any try resolve `$media->group->thumbnail[0]->attributes()` you can get this error. – Enyby Mar 01 '17 at 05:23
11

SimpleXML's methods always return objects, which are themselves linked to the original document (some internal thingy related to libxml.) If you want to store that data for later use, cast it as a string, like this:

$videoobj[$i]['url'] = (string) $attrs['url'];
$videoobj[$i]['thumb'] = (string) $attrs['url']; 
$videoobj[$i]['title'] = (string) $media->group->title;
Josh Davis
  • 28,400
  • 5
  • 52
  • 67