Page 1 of 1

Youtube API videos

Posted: Sat Sep 03, 2011 12:57 pm
by Torniquet
Not a question, just an addon to it really.

Thanks to Jacek's tutorials he made on the API, I was able to create what I needed.

These 2 functions loads the video list within a playlist and a couple of details from a single video.
function load_playlist($playlist_id)
{
	if((time() - filemtime("playlist-cache.txt")) > (3600 * 12))
	{
		$data = file_get_contents('https://gdata.youtube.com/feeds/api/pla ... st_id}?v=2'); //loads the playlist contents
		$xml = simplexml_load_string($data);
	
		foreach($xml->entry as $video)
		{
			$url = (array)$video->link[4];
			$title = $video->title; // pulls the video title
			$link = substr($url['@attributes']['href'], 0, strlen( $url['@attributes']['href']) - 4); // pulls the g.data link for the individual videos minus the ?v=2. The ?v=2 version doesnt capture the right info of the videos i required.
			$v_list[] = array("title"	=>	$title, "link"	=>	substr($link, -11)); //the 'link' is cut down to the video ID only. replace with the $link variable to use the full g.data link.
		}
		
		file_put_contents("playlist-cache.txt", serialize($v_list));
	}
	else
	{
		$v_list = sxml_unserialze(file_get_contents("playlist-cache.txt")); //smxl_funserialize is a function i found on the web due to an error unserializing simple xml data.
	}
	
	return $v_list;
}
function load_video_data($url)
{
	$data = file_get_contents("http://gdata.youtube.com/feeds/api/videos/" . $url); // Loads the individual video data.
	$xml = simplexml_load_string($data);
	$title = (array)$xml->title; // pulls the video title information
	$desc = (array)$xml->content;// pulls the video description information
	$v_data = array("title"	=>	$title[0], "content"	=>	nl2br($desc[0]), "id" => substr($xml->id, -11));//assigns the video title and description to the array.
	return $v_data;
}

The unserialize function for simplexml taken from http://tgrove.com/2009/04/06/warning-un ... ts-in-php/ (thanks :) lol)
function sxml_unserialze($str) {
return unserialize(str_replace(array('O:16:"SimpleXMLElement":0:{}', 'O:16:"SimpleXMLElement":'), array('s:0:"";', 'O:8:"stdClass":'), $str));
}

I am posting here as the tutorial section of the forum doesnt seem to get looked at all to often lol.

To see it working head to www.psi.tapt-in.net and click the watch now button in the top right corner to load the player. (Link only provided for application demo reasons.)

Thank you Jacek for your initial videos on this, I spent ages looking about working out how to use this properly and could never get my head round it. Please feel free to use this info and expand your current youtube API tutorials 8-)

Re: Youtube API videos

Posted: Tue Jun 26, 2012 7:16 am
by janvier123
very good code, but there is no example on how to actually run this code