Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SimpleXML - "Node no longer exists"

Tags:

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++;
}
like image 342
Andreas Norman Avatar asked Mar 23 '10 17:03

Andreas Norman


2 Answers

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);
}
like image 99
Björn Avatar answered Oct 06 '22 01:10

Björn


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;
like image 26
Josh Davis Avatar answered Oct 06 '22 00:10

Josh Davis