Custom Web Design & Development

Parse XML Feed with PHP Code

We are going to use PHP code to scrape content from a YouTube video XML feed and display it on our web site.

1.  We need an XML feed.  For this demo, we are using a YouTube video feed however you could do this with any XML feed from Blogger, WordPress, etc...  YouTube feeds can be grouped by a favorite Channel ID, Username, or Playlist ID.  Some code examples:

For this demo, we are using the following video playlist from Sick Science!

If you enter the URL above into your browser's address bar, you should see an RSS feed like this one below.  If you don't, your feed is either empty or the ID you've chosen is not a valid one.  Try a different feed.

RSS feed1

Now if you go to your browser's code source, you should see XML code that resembles this.  We've highlighted the nodes that we are most interested in capturing for this demo.  They are  <entry> <id> <title> <author> <name> <uri> and <published>.

feed 2 source code

If your feed is not from YouTube, chances are your Node namespaces will differ from the ones shown here.  But that's OK.  With PHP, we can customize our code as needed. 

2. Now that we have our Feed and the Nodes we want to capture, let's build our PHP code.

//******************By Nancy O.***************//
//*******Alt-Web Design & Publishing******//
//*********SAVE THIS FILE AS MY_FEED.PHP******//
$html = "";
//URL of your XML feed by user, playlist or channel ID
$feed  = "";
//Load feed xml file
$xml = simplexml_load_file($feed);
//display 6 feed entries, use more or less as desired
for($i = 0; $i < 6; $i++) {
   //define our feed nodes
   $published = $xml->entry[$i]->published;
   //optional, shorten the date
   $shortDate = date("m/d/Y", strtotime($published));
   $title = $xml->entry[$i]->title;
   $id = $xml->entry[$i]->id;
   //strip unwanted characters from ID
   $id = str_replace ("yt:video:", "", $id);
   $author = $xml->entry[$i]->author->name;
   $uri = $xml->entry[$i]->author->uri;
   //put nodes into html tags & embedded youTube player.
   $html .= "<div class='col-sm-6 col-md-4'>
<h4><a href='$uri'>$title</a></h4>
<iframe src='$id' allowfullscreen>
<small>Published: $shortDate &nbsp; By: $author></small>
//output everything to html
echo $html;

When we examine our parsed XML feed, it looks like this:


The presentation isn't exciting but it's not supposed to be.  If you view the source code you'll see it's just a plain fragment of HTML code which we defined in our PHP code above. 

For best results, use your parsed feed as a PHP server-side-include within your parent web pages. That way, your parsed feed will integrate seamlessly with your site's existing layout and styles. 


There you have it. Hope you enjoyed this tutorial on parsing  XML feeds with PHP code.