jueves, 31 de enero de 2013

Youtube Search API with PHP

In this post we will see how to use the Youtube API to use on our website. In this way we will have a video search engine online.

demo
: http://app.opnway.com/documental/




En este post veremos como utilizar la API de Youtube para utilizarla en nuestra página web. De esta forma tendremos un buscador de videos online.

Demo: 
http://app.opnway.com/documental/



<?php
    if (isset($_POST['q']))
     {
     
      if (!isset($_POST['q']) || empty($_POST['q'])) {
        die ('ERROR: Please enter one or more search keywords');
      } else {
        $q = $_POST['q']." documental";
        $q = ereg_replace('[[:space:]]+', '/', trim($q));
      }
       if (!isset($_POST['i']) || empty($_POST['i'])) {
        $i = 25;
      } else {
        $i = $_POST['i'];
      }
     
      $feedURL = "http://gdata.youtube.com/feeds/api/videos/-/{$q}?orderby=relevance&max-results=6";
      $sxml = simplexml_load_file($feedURL);
      $counts = $sxml->children('http://a9.com/-/spec/opensearchrss/1.0/');
      $total = $counts->totalResults;
      $startOffset = $counts->startIndex;
      $endOffset = ($startOffset-1) + $counts->itemsPerPage;      

      foreach ($sxml->entry as $entry) {
      
        $media = $entry->children('http://search.yahoo.com/mrss/');
        $attrs = $media->group->player->attributes();
        $watch = $attrs['url'];
        $attrs = $media->group->thumbnail[0]->attributes();
        $thumbnail = $attrs['url'];
        $yt = $media->children('http://gdata.youtube.com/schemas/2007');
        $attrs = $yt->duration->attributes();
        $length = $attrs['seconds'];
        $title =
$media->group->title;        

echo "<div style='width: 200px; float: left; margin: 5px;'><b>".substr($media->group->title, 0, 32)."</b>";
        echo "<a href='".$watch."'><img width='100%' src=\"$thumbnail\" alt=\"$title\"/></a>";
    $seg_ini =  $length;
    $horas = floor($seg_ini/3600);
    $minutos = floor(($seg_ini-($horas*3600))/60);
    $segundos = $seg_ini-($horas*3600)-($minutos*60);
echo "<class style='font-style:italic;'>".$horas.'h:'.$minutos.'m:'.$segundos.'s</class>';
    echo "</div>";
  

      }
    }
    ?>

1 comentario: