PHP: Clase simple para obtener información de videos de YouTube v1.1
Hace bastante tiempo ya, Septiembre 24 del 2010 para ser mas especifico, escribí una clase en PHP para poder obtener información de los videos de Youtube liberada bajo licencia GPL/v2.
Esta entrada tuvo muchas visitas y comentarios, así que decidí sacar la versión 1.1 con nuevas funcionalidades y mejoras en performance. El código lo pueden encontrar en este proyecto de Google Code:
En el mismo podrán hacer comentarios, sugerencias y bajarse el código con un ejemplo. También encontraran una Wiki para poder empezar a usar la clase…
En esta v1.1, podemos obtener los siguientes datos:
- Title.
- Valid (is a valid video?)
- Published.
- Updated.
- Category.
- Tags.
- Content.
- Description.
- Link.
- Images.
- Author Name.
- Author Url.
- Author Uri.
- Embed Code.
Les dejo el código para aquellos que les gusta el copy/paste…
youtube.class.php
<?php
/*
* Name: Simple Class YouTube
* Description: Get Information of YouTube video
* Site: http://www.zarpele.com.ar
* License: GNU GENERAL PUBLIC LICENSE (http://www.gnu.org/licenses/gpl.html)
* Version: 1.1
*/
class Youtube
{
var $data = '';
var $xml = '';
var $id = '';
private function youtubeCurl($url){
$browser_id = 'none';
$curl_handle = curl_init();
$options = array
(
CURLOPT_URL => $url,
CURLOPT_HEADER => false,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_USERAGENT => $browser_id
);
curl_setopt_array($curl_handle, $options);
$server_output = curl_exec($curl_handle);
curl_close($curl_handle);
return $server_output;
}
public function __construct($id)
{
if (strlen($id) >= 22)
{
parse_str( parse_url( $id, PHP_URL_QUERY ) );
$this->id = $v;
}
else
{
$this->id = $id;
}
$url = 'http://gdata.youtube.com/feeds/videos/' . $this->id;
$server_output = $this->youtubeCurl($url);
if($server_output == 'Invalid id'){
return false;
}else{
$this->data = $server_output;
$description = $this->prepareDescription();
$this->xml = new SimpleXMLElement($this->data);
$this->xml->addChild('description', $description);
return true;
}
}
public function getData(){
return $this->data;
}
public function getXml(){
return $this->xml;
}
public function valid(){
if(empty($this->data)){
return false;
}else{
return true;
}
}
/* DATA VIDEO */
public function getTitle(){
if ($this->valid()){
return $this->xml->title;
}else{
return false;
}
}
public function getPublished()
{
if ($this->valid()){
return $this->xml->published;
}else{
return false;
}
}
public function getUpdated()
{
if ($this->valid()){
return $this->xml->updated;
}else{
return false;
}
}
public function getCategory()
{
if ($this->valid()){
$category = '';
for ($i = 0; $i < count($this->xml->category);$i++){
if ($this->xml->category[$i]['scheme'] == 'http://gdata.youtube.com/schemas/2007/categories.cat'){
$category = $this->xml->category[$i]['label'];
break;
}
}
return $category;
}else{
return false;
}
}
public function getTags(){
if ($this->valid()){
$tags = array();
for ($i = 0; $i < count($this->xml->category);$i++){
if ($this->xml->category[$i]['scheme'] == 'http://gdata.youtube.com/schemas/2007/keywords.cat'){
$name = $this->xml->category[$i]['term'];
array_push($tags, $name);
}
}
return $tags;
}else{
return false;
}
}
public function getContent()
{
if ($this->valid()){
return $this->xml->content;
}else{
return false;
}
}
public function getDescription()
{
if ($this->valid()){
return $this->xml->description;
}else{
return false;
}
}
private function prepareDescription()
{
$startString = "<media:description type='plain'>";
$endString = "</media:description>";
$starLocation = strpos($this->data, $startString);
$tempString = substr($this->data, $starLocation);
$endLocation = strpos($tempString, $endString);
$description = substr($tempString, 0, $endLocation);
if (empty($description))
{
$description=false;
}
else
{
$description = substr($description,strlen($startString));
}
return $description;
}
public function getUrl()
{
if ($this->valid()){
return 'http://www.youtube.com/watch?v='.$this->id;
}else{
return false;
}
}
public function getImageUrl($option)
{
if ($this->valid()){
if($option == 'default'){
return 'http://i.ytimg.com/vi/'.$this->id.'/default.jpg';
}
if($option == 0){
return 'http://i.ytimg.com/vi/'.$this->id.'/0.jpg';
}
if($option == 1){
return 'http://i.ytimg.com/vi/'.$this->id.'/1.jpg';
}
if($option == 2){
return 'http://i.ytimg.com/vi/'.$this->id.'/2.jpg';
}
if($option == 3){
return 'http://i.ytimg.com/vi/'.$this->id.'/3.jpg';
}
}else{
return false;
}
}
/* AUTHOR MEHTODS */
public function getAuthorName(){
if ($this->valid()){
return $this->xml->author->name;
}else{
return false;
}
}
public function getAuthorUrl(){
if ($this->valid()){
return 'http://www.youtube.com/user/'.$this->getAuthorName();
}else{
return false;
}
}
public function getAuthorUri(){
if ($this->valid()){
return $this->xml->author->uri;
}else{
return false;
}
}
/* see: http://code.google.com/apis/youtube/player_parameters.html */
public function getEmbeb($options = NULL)
{
$width = $options['width'];
if (!isset($options['width'])){
$width = 425;
} //Width
unset($options['width']);
$height = $options['height'];
if (!isset($options['height'])){
$height = 349;
} //Height
unset($options['height']);
$secure = '';
if (isset($options['https'])){
if ($options['https'] == 1){
$secure = 's';
unset($options['https']);
}else{
$secure = '';
unset($options['https']);
}
}
if(empty($options)){
$exclamation = '"';
}else{
$exclamation = '?';
}
$embeb_code = '<iframe class="youtube-player" type="text/html" width="'.$width.'" height="'.$height.'" src="http'.$secure.'://www.youtube.com/embed/'.$this->id.$exclamation;
$i = 1;
foreach($options as $key => $value){
if($i == count($options)){
$embeb_code .= $key.'='.$value.'"';
}else{
$embeb_code .= $key.'='.$value.'&';
}
$i++;
}
$embeb_code .= '></iframe>';
return $embeb_code;
}
}
?>
sample.php
<?php
/*
* Name: Simple Class Info YouTube
* Description: Get Information of YouTube video
* Site: http://www.zarpele.com.ar
* License: GNU GENERAL PUBLIC LICENSE (http://www.gnu.org/licenses/gpl.html)
* Version: 1.1
*/?>
<?php
require_once 'youtube.class.php';
$url = 'http://www.youtube.com/watch?v=5ocq6_3-nEw';
$youtube = new Youtube($url);
//$id = '5ocq6_3-nEw';
//$youtube = new Youtube($id);
?>
<h2>Video Data</h2>
<p>
<strong>Title: </strong>
<?php echo $youtube->getTitle()?>
</p>
<p>
<strong>Valid: </strong>
<?php var_dump($youtube->valid())?>
</p>
<p>
<strong>Published: </strong>
<?php echo $youtube->getPublished()?>
</p>
<p>
<strong>Updated: </strong>
<?php echo $youtube->getUpdated()?>
</p>
<p>
<strong>Category: </strong>
<?php echo $youtube->getCategory()?>
</p>
<p>
<strong>Tags: </strong>
<?php var_dump($youtube->getTags())?>
</p>
<p>
<strong>Content: </strong>
<?php echo $youtube->getContent()?>
</p>
<p>
<strong>Description: </strong>
<?php echo $youtube->getDescription()?>
</p>
<p>
<strong>Link: </strong>
<?php echo $youtube->getUrl()?>
</p>
<p>
<strong>Imagen: </strong>
<?php echo $youtube->getImageUrl('default')?><br/>
<img src="<?php echo $youtube->getImageUrl('default')?>" alt=""/>
<img src="<?php echo $youtube->getImageUrl(0)?>" alt=""/>
<img src="<?php echo $youtube->getImageUrl(1)?>" alt=""/>
<img src="<?php echo $youtube->getImageUrl(2)?>" alt=""/>
<img src="<?php echo $youtube->getImageUrl(3)?>" alt=""/>
</p>
<h2>Author Data</h2>
<p>
<strong>Author Name: </strong>
<?php echo $youtube->getAuthorName()?>
</p>
<p>
<strong>Author Url: </strong>
<?php echo $youtube->getAuthorUrl()?>
</p>
<p>
<strong>Author Uri: </strong>
<?php echo $youtube->getAuthorUri()?>
</p>
<p>
<strong>Video: </strong><br/>
<?php $options = array('autoplay' => 1);?>
<?php echo $youtube->getEmbeb($options);?>
</p>
Google Code Page | http://code.google.com/p/simple-class-youtube/
Deja tu comentario…
Puedes seguir cualquier respuesta a esta entrada mediante el canal RSS 2.0. Puedes dejar un comentario o enviar un trackback desde tu propio sitio.















[...] de ir mejorando el codigo, esta liberado bajo licencia GPL/v2. ACTUALIZACION 02-07-2011 Lanzada la versión 1.1 Easy AdSense by Unreal $$('div.d1868').each( function(e) { [...]
oye soy novaton en php y me pregunto como podria mandar a llamar el metodo, ya subi el archivo php a mi servidor pero como le mando el parametro id y como me devuelve los datos? hay que crear botones o que’
si ejecutaste el sample.php y ves estas lineas…
es ahi donde se setea. Para hacerlo de forma dinamica, tendrias que leer un poco sobre el paso de variables a un script en PHP.
http://php.net/manual/en/reserved.variables.post.php/
http://www.php.net/manual/en/reserved.variables.get.php
Saludos…
[...] PHP: Clase simple para obtener información de videos de YouTube v1.1 – 231 Hits [...]
gracias tio, el codigo me ha servido bastante.
Hola, estoy utilizando esta clase que pinta muy bien. Pero al usarla me aparece el siguiente error:
Fatal error: Call to undefined function curl_init() in (…)youtube.php on line 18
Es necesario añadir alguna clase más? o la API de Youtube?
Hola Tamara,
Esa función en propia de PHP,
Usas Windwos o Linux?
Saludos.
Hola Zarpele, vi otro comentario donde lo solucionaba (tenia el mismo caso que el que utiliza xampp), tenia que habilitar la libreria curl_init().
Igualmente, una vez he solucionado este problema, se me presenta otro error, y es el de “Undefined variable: v in youtube.php” y estado mirando el código y no se de donde aparece la variable $v.
Esta variable se encuentra en la linea 37 de tu clase.
Muchísimas gracias por contestar tan pronto y preocuparte por las dudas o problemas que te planteamos, es de de agradecer.
No puedo reproducir dicho error.
Asegurate de bajar el codigo desde aqui: http://code.google.com/p/simple-class-youtube/downloads/
este funciona correctamente.
Saludos.
Hola Zarpele,
El problema era que ponia el enlace nuevo de youtube, el cual no contiene en su url el parámetro ‘v’ y por eso me fallaba.
Igualmente, te quería comentar que, en local al menos, con mucha frequencia se da el error: Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\….\youtube.php on line 28
Lo que hago es guardar la url del video en bbdd y cada vez que quiero mostrar el video hago que me genere el embed, y estoy planteandome para solucionar el error guardar el embed directamente en base de datos en lugar de la url. ¿Tu como lo haces? A alguien más le sucede el mismo error?
Hola que tal me gusta lo que estas haciendoo! yo he estoy tratando de hacer lo siguiente : listar los URL’s de un determinado USuario de Youtube osea todas sus UPLOADS, para poder listar sus Videos y tbm de paso los thumbails como pequeña imagen… que tal te dejo el URL del gdata respectivo NO me sale =D ayudame ? http://gdata.youtube.com/feeds/api/users/maddijanemusic/uploads seguire Intentando si me llega a salir lo que quiero mostrar enviare el codigo =)
Si desean el método de visitas del video es este:
public function Visitas(){
if ($this->valid()){
preg_match_all(“//”,$this->data,$count);
return $count[2][0];
}else{
return false;
}
}
Muy bueno, gracias por tu aporte…
Eddy trate de poner tu codigo de visitas pero me saca este error de este codigo:
return $count[2][0];
y me sale este error en la web:
Parse error: syntax error, unexpected T_RETURN in /home/content/12/8327212/html/construct2/youtube.class.php on line 67
si sirve