Nov 27, 2011

Youtube Video Scraping | Fetch Youtube Video Via RSS

Always I wondered to display youtube videos below my posts or for some other purpose. But always had to use some plugins or some complicated scripts. So finally coded for you people a small function which will fetch or scrape youtube videos through GDATA RSS.



[php]
<?php
$search = 'linkinpark';//Search Term
$file = file_get_contents('http://gdata.youtube.com/feeds/base/videos?q='.$search.'&client=ytapi-youtube-search&v=2');
$rss = new SimpleXMLElement($file);
$limit = '10'; //Videos Limit to display
$ctr = '0';
foreach($rss->entry as $idx => $key)
{
if($ctr == $limit)
{
break;
}
else{
echo '<div id="video">';
echo '<p class="title">'.$key->title.'</p>';
echo '<p class="video">'.$key->content.'</p>';
echo '</div>';
$ctr++;
}
}
?>
[/php]


My idea behind getting the videos is first to fetch the entire contents of the GDATA RSS page using file_get_contents

After storing the RSS into a file as a string, we will convert it into proper XML using SimpleXMLElement

We store this XML version into a variable which consists of arrays and objects.

Finally we bring the foreach and break down the array into pieces. Thats it. Go and test it yourself.

This function is the basic version, I am sure you can modify it and make more flexible.


download

2 comments :

  1. Heri Azhar3/3/14 1:43 AM

    can you help how to get youtube description, rating and view ?

    ReplyDelete
  2. just play with XML, you'll come to know, its really simple

    ReplyDelete