Friday, May 24, 2013

Searching Live Events from YouTube

I was slightly surprised and also somewhat annoyed when I found out that there is no way to make a free text search for finding YouTube Live Events with YouTube Data API. The Live Events section of the API is still experimental, but I feel the search functionality is so essential that is almost strange that it is missing.

Sure, you can filter the search results with some simple comparisons (see https://developers.google.com/youtube/2.0/developers_guide_protocol_partial), but I was unable to find a wildcard for titles or description/summary searches, similar to SQL's functionality WHERE title LIKE '%bbc%'.

So if you want to search live events, you have at least these two options:

1.  Load everything from one live event feed and make a string search over the xml result.
2. Do not use YouTube Data API, but use the web page search instead.
Example with PHP
The next code snippet loads the web page url, finds the video ids, and loads the detailed information about the live event with YouTube Data API.

// get your keywords and page index from page request 
// $searchwords    = $_REQUEST["searchwords"] 
// $page           = $_REQUEST["page"] 
$page = 1; 
$searchwords = 'arirang'; 
// create url 
$search_url = "http://www.youtube.com/results?search_query=" 
             ."$searchwords&filters=live&lclk=live&page=$page"; 
// load web page contents 
$html = file_get_contents($search_url)
// now search the content ids 
$ids = array();                      // to store the found ids 
$idlength = 11;                      // length of youtube videoid 
$attr = 'data-context-item-id="';    // video id in the html 
$pos = strpos($html,$attr,0);        // pos in html 
while ($pos!==FALSE) { 
    $ids[] = substr($html, $pos+strlen($attr), $idlength)
    $pos=strpos($html,$attr,$pos+$idlength)
} 
// now you can loop the ids and load live events for each id 
foreach ($ids as $id) { 
    $xmlurl = "http://gdata.youtube.com/feeds/api/videos/" 
             ."$id?v=2&prettyprint=true"; 
    $xmldata = file_get_contents($xmlurl)
    // parse live event here etc... 
} 

2 comments:

Brent Fox said...

Could this be used to embed currently live YouTube videos?

Jussi said...

Hi! Sure, I have not tried it, but I suppose you just need to create embed code using the live event ID.