Search code examples
phpsimplexmlyoutube-api

Fetch video id from a youtube playlist using PHP-SimpleXML


I'm fetching a few videos from a Youtube playlist using SimpleXML and the Youtube API. I managed to get the title of each video but can´t figure out how to get the video IDs.

How do I get the <yt:videoid> tag?

This is what I got so far:

$xml = simplexml_load_file('http://gdata.youtube.com/feeds/api/playlists/ ID ');

$videos=array();

foreach ($xml->entry as $video) {
      $vid = array();
      $vid['title'] = $video->title; // <- This Works

      $media = $video->children('http://search.yahoo.com/mrss/');
      $yt = $media->group->children('http://gdata.youtube.com/schemas/2007');
      $vid['id']=$yt->videoid;  // <- Not Working

      $videos[]=$vid;
}

Solution

  • Just a wild guess here: You are just outputting 'title' but you try to do something else with 'videoid'? Because what you are adding to the $vid array are not strings, but SimpleXMLElement-Objects. You have to cast them manually:

    $vid['id']= (string) $yt->videoid;
    

    Other than that, your code works OK.