<?
/**
 * YouTube Parser
 * Greg Arutunyan 8/3/2011
 * Version 1.0
 *
 * @Array   All parameter should be passed in an array
 * Array[KEY]=>[VALUE]
 */

/***** USAGE ******
$data = array(	"searchTerm" => $search,
				"resultSize" => $size,
			  );
*/

function ytcurl($url)
{
	$Timeout = 5;
		
	###### INIT ############
	$ch = curl_init($url);
	###### CURL & OPTION #####
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_TIMEOUT, $Timeout);
	$data = curl_exec($ch);
	curl_close($ch);
	return $data;
}

/* YOUTUBE RESULTS */
function loadYouTubeResults($data) {
	$youTubeResults = false;
	
	if(empty($data['searchTerm'])) {
		return $youTubeResults;
	}
	
	$searchTerm = $data['searchTerm'];
	$resultSize = empty($data['resultSize']) ? 3 : $data['resultSize'];
	
	// set feed URL
	$feedURL = 'http://gdata.youtube.com/feeds/api/videos?q='.$searchTerm;
	
	//$data = ytcurl($feedURL);
	// read feed into SimpleXML object
	$sxml = simplexml_load_file($feedURL);
	
	$resultCount = count($sxml->entry);
	$resultAmount = $resultCount < $resultSize ? $resultCount : $resultSize;
	$count = 0;
	
	foreach ($sxml->entry as $entry) {
		if($count == $resultAmount) break;
				
		// get nodes in media: namespace for media information
    $media = $entry->children('http://search.yahoo.com/mrss/');
		
		// get the title
		$title = $media->group->title;
		
		// get the author
		$author = $entry->author->name;
		
		// get the description
		$description = $media->group->description;
		
		// get video player URL
    $attrs = $media->group->content->attributes();
    $watch = $attrs['url'];
		
		// get video thumbnail
    $attrs = $media->group->thumbnail[0]->attributes();
    $thumbnail = $attrs['url'];
		
		// get <yt:duration> node for video length
    $yt = $media->children('http://gdata.youtube.com/schemas/2007');
    $attrs = $yt->duration->attributes();
    $length = $attrs['seconds'];
		
		// get <yt:stats> node for viewer statistics
    $yt = $entry->children('http://gdata.youtube.com/schemas/2007');
    $attrs = $yt->statistics->attributes();
    $viewCount = $attrs['viewCount'];
		
		$youTubeResults[$count]['title'] = $title;
		$youTubeResults[$count]['description'] = $description;
		$youTubeResults[$count]['author'] = $author;
		$youTubeResults[$count]['thumbnail'] = $thumbnail;
		$youTubeResults[$count]['watch'] = $watch;
		$youTubeResults[$count]['length'] = $length;
		$youTubeResults[$count]['viewCount'] = $viewCount;
		
		$count++;
	}
	
	return $youTubeResults;
}

?>