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, 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 = "" 
// 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)
// now you can loop the ids and load live events for each id 
foreach ($ids as $id) { 
    $xmlurl = "" 
    $xmldata = file_get_contents($xmlurl)
    // parse live event here etc...