3
Ene
09

Tips: Parseando con PHP el html de Youtube

PHP:
  1. <?
  2.  
  3. class Youtube{
  4. function getVideosUser($user,$view){
  5.         //Carga la Web  de Youtube
  6.         $ch = curl_init();
  7.         $timeout = 5; // si llega hasta 0 tiempo agotado
  8.         switch($view){
  9.             case "mis_videos":
  10.                 $url='http://www.youtube.com/profile?user='.$user.'&view=videos';
  11.             break;
  12.             default:
  13.                     $url='http://www.youtube.com/profile?user='.$user.'&view=favorites';
  14.             break;
  15.         }
  16.         curl_setopt ($ch, CURLOPT_URL,$url);
  17.         curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
  18.         curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  19.  
  20.         // Obtiene el HTML de Youtube
  21.         $file_contents = curl_exec($ch);
  22.         curl_close($ch);
  23.         $pagina=$file_contents;
  24. // Utilizo expresiones regulares, en las partes que se repite el código
  25. if(preg_match_all('!<img\s+title="([^"]*)"\s+src="([^"]*)"\s+class="vimg120"\s+qlicon="([^"&]+)"\s+alt="([^"]*)">!Usi', $pagina, $info, PREG_SET_ORDER)) {
  26.           foreach($info as $video) {
  27.               $videos[] = array(
  28.           'titulo' => $video[1],
  29.               'image' => $video[2],
  30.               'id' => $video[3]
  31.               );
  32.           }
  33.       }
  34.  
  35.     return $videos;
  36. }
  37.  
  38. }
  39.  
  40. $videos=new Youtube();
  41. echo "<pre>";
  42. //Favoritos
  43. print_r($videos->getVideosUser("bedomax","favoritos"));
  44. //Mis videos
  45. //print_r($videos->getVideosUser("bedomax","videos"));
  46. echo "</pre>";
  47.  
  48. ?>

Gracias que PHP hereda características de Perl, podemos utilizar expresiones regulares para manejar Strings. Aqui les dejo una clase que contiene un método que consulta los vídeos subidos y favoritos de un usuario de Youtube, ademas utilizo curl para obtener el html de Youtube y poder manipularlo con preg_match_all y obtengo en un array el resultado.

Array
(
[0] => Array
(
  [titulo] =>Titulo del Video
  [image] => http://i4.ytimg.com/vi/k3kRuJhIVIo/default.jpg
  [id] => k3kRuJhIVIo
)
)

Descargar el Código

por: maximiliano con en Código, PHP, Tips