Usare Google Data Protocol per integrare Youtube nella propria applicazione PHP

Posted on dicembre 1st, 2011. Written by Dimitri De Franciscis.


Usare Google Data Protocol per integrare Youtube nella propria applicazione PHP

Google Data Protocol è un insieme di standard creati dal colosso di Mountain View mirati all’interscambio di dati fra applicazioni sul web. Fra le grandi innovazioni di questo protocollo possiamo annoverare:

  • utilizzo di servizi di tipo REST per accedere ai dati;
  • standardizzazione e completa apertura al pubblico dei formati XML;
  • utilizzo del web semantico, per facilitare la classificazione, manipolazione e (essendo una creatura di Google) ricerca dei dati da parte di processi automatici, ovvero senza l’intervento umano.

Essendo essenzialmente un formato di interscambio, è completamente agnostico rispetto al linguaggio di programmazione utilizzato per accedervi; ciò ha portato alla creazione di moltissime librerie in diversi linguaggi: PHP, Java, Python, Ruby, eccetera. Noi però vedremo come sia davvero molto semplice interpretare “a mano” questi messaggi XML, utilizzando le funzionalità di base messe a disposizione da PHP.

Creare una pagina di ricerca

Vediamo un esempio che riesce a mettere in mostra molti dei dati a nostra dispozione, ovvero una pagina di ricerca dei video. Per prima cosa, diamo un’occhiata all’XML che ci viene restituito dalla query:

<?xml version='1.0' encoding='UTF-8'?>
<feed xmlns="http://www.w3.org/2005/Atom"
    xmlns:media="http://search.yahoo.com/mrss/"
    xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/"
    xmlns:gd="http://schemas.google.com/g/2005"
    xmlns:yt="http://gdata.youtube.com/schemas/2007">
  <id>http://gdata.youtube.com/feeds/api/videos</id>
  <updated>2011-11-27T11:28:23.460Z</updated>
  <category scheme="http://schemas.google.com/g/2005#kind" term="http://gdata.youtube.com/schemas/2007#video"/>
  <title type="text">YouTube Videos matching query: ciao</title>
  <logo>http://www.youtube.com/img/pic_youtubelogo_123x63.gif</logo>
  <link rel="alternate" type="text/html" href="http://www.youtube.com"/>
  <link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml"
  href="http://gdata.youtube.com/feeds/api/videos"/>
  <link rel="http://schemas.google.com/g/2005#batch" type="application/atom+xml"
  href="http://gdata.youtube.com/feeds/api/videos/batch"/>
  <link rel="self" type="application/atom+xml"
  href="http://gdata.youtube.com/feeds/api/videos?q=ciao&amp;start-index=1&amp;max-results=25"/>
  <link rel="next" type="application/atom+xml"
  href="http://gdata.youtube.com/feeds/api/videos?q=ciao&amp;start-index=26&amp;max-results=25"/>
  <author>
    <name>YouTube</name>
    <uri>http://www.youtube.com/</uri>
  </author>
  <generator version="2.1" uri="http://gdata.youtube.com">YouTube data API</generator>
  <openSearch:totalResults>183383</openSearch:totalResults>
  <openSearch:startIndex>1</openSearch:startIndex>
  <openSearch:itemsPerPage>25</openSearch:itemsPerPage>
  <entry>
    <id>http://gdata.youtube.com/feeds/api/videos/pnVbfO-jw_s</id>
    <published>2008-03-03T05:58:34.000Z</published>
    <updated>2011-11-26T06:50:14.000Z</updated>
    <category scheme="http://schemas.google.com/g/2005#kind" term="http://gdata.youtube.com/schemas/2007#video"/>
    <category scheme="http://gdata.youtube.com/schemas/2007/categories.cat" term="Film" label="Film e animazione"/>
    <category scheme="http://gdata.youtube.com/schemas/2007/keywords.cat" term="Ciao"/>
    <category scheme="http://gdata.youtube.com/schemas/2007/keywords.cat" term="Alessandro"/>
    <category scheme="http://gdata.youtube.com/schemas/2007/keywords.cat" term="Calza"/>
    <category scheme="http://gdata.youtube.com/schemas/2007/keywords.cat" term="Yen"/>
    <category scheme="http://gdata.youtube.com/schemas/2007/keywords.cat" term="Tan"/>
    <category scheme="http://gdata.youtube.com/schemas/2007/keywords.cat" term="cytan"/>
    <title type="text">CIAO Trailer</title>
    <content type="text">Visit ciaomovie.com for more details.</content>
    <link rel="alternate" type="text/html"
    href="http://www.youtube.com/watch?v=pnVbfO-jw_s&amp;feature=youtube_gdata"/>
    <link rel="http://gdata.youtube.com/schemas/2007#video.responses" type="application/atom+xml"
    href="http://gdata.youtube.com/feeds/api/videos/pnVbfO-jw_s/responses"/>
    <link rel="http://gdata.youtube.com/schemas/2007#video.related" type="application/atom+xml"
    href="http://gdata.youtube.com/feeds/api/videos/pnVbfO-jw_s/related"/>
    <link rel="http://gdata.youtube.com/schemas/2007#mobile" type="text/html" href="http://m.youtube.com/details?v=pnVbfO-jw_s"/>
    <link rel="self" type="application/atom+xml" href="http://gdata.youtube.com/feeds/api/videos/pnVbfO-jw_s"/>
    <author>
      <name>cytan8</name>
      <uri>http://gdata.youtube.com/feeds/api/users/cytan8</uri>
    </author>
    <gd:comments>
      <gd:feedLink href="http://gdata.youtube.com/feeds/api/videos/pnVbfO-jw_s/comments" countHint="135"/>
    </gd:comments>
    <media:group>
      <media:category label="Film e animazione" scheme="http://gdata.youtube.com/schemas/2007/categories.cat">Film</media:category>
      <media:content url="http://www.youtube.com/v/pnVbfO-jw_s?version=3&amp;f=videos&amp;app=youtube_gdata"
      type="application/x-shockwave-flash" medium="video" isDefault="true" expression="full" duration="103" yt:format="5"/>
      <media:content url="rtsp://v4.cache1.c.youtube.com/CiILENy73wIaGQn7w6PvfFt1phMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp"
      type="video/3gpp" medium="video" expression="full" duration="103" yt:format="1"/>
      <media:content url="rtsp://v4.cache6.c.youtube.com/CiILENy73wIaGQn7w6PvfFt1phMYESARFEgGUgZ2aWRlb3MM/0/0/0/video.3gp"
      type="video/3gpp" medium="video" expression="full" duration="103" yt:format="6"/>
      <media:description type="plain">Visit ciaomovie.com for more details.</media:description>
      <media:keywords>Ciao, Alessandro, Calza, Yen, Tan, cytan</media:keywords>
      <media:player url="http://www.youtube.com/watch?v=pnVbfO-jw_s&amp;feature=youtube_gdata_player"/>
      <media:thumbnail url="http://i.ytimg.com/vi/pnVbfO-jw_s/0.jpg" height="360" width="480" time="00:00:51.500"/>
      <media:thumbnail url="http://i.ytimg.com/vi/pnVbfO-jw_s/1.jpg" height="90" width="120" time="00:00:25.750"/>
      <media:thumbnail url="http://i.ytimg.com/vi/pnVbfO-jw_s/2.jpg" height="90" width="120" time="00:00:51.500"/>
      <media:thumbnail url="http://i.ytimg.com/vi/pnVbfO-jw_s/3.jpg" height="90" width="120" time="00:01:17.250"/>
      <media:title type="plain">CIAO Trailer</media:title>
      <yt:duration seconds="103"/>
    </media:group>
    <gd:rating average="4.8023257" max="5" min="1" numRaters="258" rel="http://schemas.google.com/g/2005#overall"/>
    <yt:statistics favoriteCount="472" viewCount="304821"/>
  </entry>

  [...]
</feed>

 

Per ottenere questo feed dobbiamo semplicemente eseguire una richiesta
HTTP a questo indirizzo:

http://gdata.youtube.com/feeds/api/videos?q=ciao

Possiamo notare che c’è un elemento <entry> per ogni video trovato, non ci
resta quindi che prendere questi dati e formattarli nella maniera che più ci
piace! La documentazione è molto completa, la potete trovare sulla pagina dedicata su Google Code.

Ecco quindi il codice PHP per una pagina di ricerca video che non fa uso di librerie esterne:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
  <title>Youtube API</title>
  <style type="text/css">
#container {
  width: 960px;
  font-family: Helvetica;
}
div.entry {
  clear: both;
  width: 640;
  border-top: 1px solid #eee;
}
div.entry h4 {
  margin-bottom: 5px;
}
div.keywords {
  font-size: 0.8em;
  margin-bottom: 5px;
}
div.thumbnail {
  clear: left;
  float: left;
  width: 120px;
  height: 90px;
}
div.description {
  width: 740px;
  margin-left: 135px;
}

br.clearfix {
  clear: both;
}
  </style>
</head>
<body>
  <div id="container">
<h1>Esempi Youtube API</h1>

<h3>Ricerca video</h3>

<?php
$query = "";

if (isset($_GET['q'])) {
  $query = $_GET['q'];
}
?>

<form>
<input name="q" value="<?php echo filter_var($query, FILTER_SANITIZE_SPECIAL_CHARS); ?>" />
  <button type="submit">Cerca</button>
</form>

<?
if ($query) {
  $xml = simplexml_load_file('http://gdata.youtube.com/feeds/api/videos?'. $_GET['q']);
  $namespaces = $xml->getNameSpaces(true);

  foreach($xml->entry as $entry) {
    $id = $entry->id;
    $media = $entry->children($namespaces['media']);
    $videoURL = "";
    foreach($entry->link as $link) {
      if ($link['rel'] == 'alternate') {
        $videoURL = $link['href'];
        break;
      }
    }
    $title = $media->group->title;
    $description = $media->group->description;
    $keywords = $media->group->keywords;
    $thumb = $media->group->xpath("media:thumbnail[@width='120' and @height='90']");
    ?>
    <div class="entry">
      <h4><?php echo $title ?></h4>
      <div class="keywords">Keywords: <em><?php echo $keywords; ?></em></div>
      <div class="thumbnail">
        <a href="<?php echo $videoURL; ?>">
          <img src="<?php echo($thumb[0]['url']); ?>" width="120" height="90" />
        </a>
      </div>
      <div class="description">
        <?php echo $description; ?>
      </div>
      <br class="clearfix" />
    </div>
  <?php
  }
} // if ($query)
?>
  </div>
</body>
</html>

 

Ovviamente le personalizzazioni sono fondamentali, quindi il consiglio è come al solito di sperimentare!

Links

  • http://www.ogamebay.com/swtor-credits.html swtor credits

    Wie das Gefühl, wie wir durch die H?hen und Tiefen sind es nicht. Ein einfaches Ziel, k?nnen die Fans auch Angst, wie flach fan!

HS su Facebook!