Foros del Web » Programando para Internet » PHP » Frameworks y PHP orientado a objetos »

Clase de parseo en links e imagenes [aporte]

Estas en el tema de Clase de parseo en links e imagenes [aporte] en el foro de Frameworks y PHP orientado a objetos en Foros del Web. Bueno...aca una clase para parsear: - TITLE de la pagina - META TAGS - ENLACES - IMAGENES - VIDEOS *** new *** Código PHP: <?php ...
  #1 (permalink)  
Antiguo 09/07/2009, 09:36
Avatar de Italico76  
Fecha de Ingreso: abril-2007
Mensajes: 3.303
Antigüedad: 17 años
Puntos: 292
Clase de parseo en links, imagenes, videos y mas [APORTE]

Bueno...aca una clase para parsear:

- TITLE de la pagina
- META TAGS
- ENLACES
- IMAGENES
- VIDEOS *** new ***

Código PHP:
<?php
//// By Pablo Bozzolo (2009)
///
///  Expresion regular para links by Chirp Internet: www.chirp.com.au


Include "links.class.php";
Include 
"video.class.php";

class 
tagParser {  // clase 
//////////////////////////////////////
  
private   $html
  
  protected 
$title// title de la pagina
  
protected $titleProcesado=FALSE;       #bool
  
  
protected $metatags;
  protected 
$metatagsProcesados=FALSE;   #bool
  
  
protected $enlaces;
  private   
$cantEnlaces;
  private   
$contadorEnlaces;
  protected 
$enlacesProcesados=FALSE;    #bool
  
  
protected $imagenes;  
  private   
$cantImagenes;    
  private   
$contadorImagenes;  
  protected 
$imagenesProcesadas=FALSE;   #bool
  
  
protected $videos;
  private   
$cantVideos;
  private   
$contadorVideos;
  protected 
$videosProcesados=FALSE;     #bool
  //////////////////////////////////////  
  
  
function __construct($html){ 
   
$this->html=$html;    
   
$this->html =str_replace("\"" "'" ,$this->html);  //reemplazo comillas dobles por simples para simplificar expr reg   
  

  
  
//// LINKS
  
  
function parseLinks(){      
    
preg_match_all("/<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>/siU",$this->html,$this->enlaces);  // expresion para parseo de LINKS    
    
$this->cantEnlaces=count($this->enlaces[2]);
    
$this->contadorEnlaces=0// procesados
    
$this->enlacesProcesados=TRUE;

  }    

  function 
getLinkCount(){
    if (
$this->enlacesProcesados){  
      return(
$this->cantEnlaces);
    }else{
      echo 
"ERROR: NO HA PROCESADO NINGUN ENLACE!";
      exit;     
   }      
  }
  
  function 
getLink(){       
    
$uri str_replace("'","",$this->enlaces[2][$this->contadorEnlaces]);     
    
$diana $this->enlaces[3][$this->contadorEnlaces];    
    
$this->contadorEnlaces++;
    
$linktogive = new link ($uri);
    
$linktogive->setDiana($diana);
    return (
$linktogive);   
  }  
  
  
//// Imagenes
  
  
function parseImages(){  
    
preg_match_all("|<img\s[^>]*src=(\"??)([^\" >]*?)\\1[^>]*/>|siU",$this->html,$this->imagenes);  // expresion para parseo de LINKS    
    
$this->cantImagenes=count($this->imagenes[1]); // BUG fixed 
    
$this->contadorImagenes=0// procesados
    
$this->imagenesProcesadas=TRUE;    
  }
  
  function 
getImageCount(){
    if (
$this->imagenesProcesadas){  
      return(
$this->cantImagenes);
    }else{
      echo 
"ERROR: NO HA PROCESADO NINGUNA IMAGEN!";
      exit;     
   }      
  }
    
  function 
getImage(){    
    
$img     str_replace("'","",$this->imagenes[2][$this->contadorImagenes]); 
    
$imgtogive = new Img($img); 
    
$this->contadorImagenes++;
    return (
$imgtogive);   
  }  

  
//// TITLE de la pagina
  
  
function parseTitle(){
    
preg_match('|<title>(.*?)</title>|is',$this->html,$title);      
    
$this->title=$title[1];
    
$this->titleProcesado=TRUE;
  }
  
  function 
getTitle(){
    if (
$this->titleProcesado){  
      return (
$this->title);
    }else{  
      echo 
"ERROR: NO HA PROCESADO NINGUN TITLE";
      exit;     
    } 
  }
  
  
//// META-tags 
  
  
function parseMetas(){
    
save_file("parser.tmp",$this->html); // generar uno q no exista        
    
$this->metatags get_meta_tags("parser.tmp");
    
$this->titleProcesado=TRUE;
  }    
  
  function 
getMeta($tag){
    return (
$this->metatags[$tag]);
  }
  
  
//// VIDEOS
  
  
function parseVideos(){
  
    
// YouTube    
    
preg_match_all'/value=\'(http:\/\/[^&"\'\s]+)/i',$this->html,$this->videos);        
        
    
// MeyaCafe
    
preg_match_all('|http://www.metacafe.com/fplayer/(.*?).swf|',$this->html,$metacafe);    
    
    for(
$i=0;$i<count($metacafe[1]);$i++){       // lo paso al mismo array
      
$this->videos[1][]="http://www.metacafe.com/fplayer/{$metacafe[1][$i]}.swf";
     }
    

    
$this->cantVideos=count($this->videos[1]);     
    
$this->contadorVideos=0
    
$this->videosProcesados=TRUE;                
  }
  
   function 
getVideoCount(){
    if (
$this->videosProcesados){  
      return(
$this->cantVideos);
    }else{
      echo 
"ERROR: NO HA PROCESADO NINGUN VIDEO";
      exit;     
   }      
  }  
  
  function 
getVideo(){ // podria recibir el tipo como parametro (YouTube,MetaCafe,etc)    

    
$videotoget = new video($this->videos[1][$this->contadorVideos]);
    
$this->contadorVideos++;
    return (
$videotoget); 
  }
    

}
# fin de la clase


  
Function save_file ($file,$content){  
  
//guardo $content en un archivo
    
if (!$handle fopen($file,"w+b")){
      echo 
"Error: archivo no pudo ser abierto";
      return (
False);
      exit;
    }  
    if (!
fwrite ($handle$content)){
      echo 
"Se ha producido un error y nada se ha escrito";
      return (
False);
      exit;
   }  
   return (
true);  // todo ok
  
}
    

?>
Para probarlo deben bajarse las otras clases que puse mas abajo y aca un ejemplo de uso:

Código PHP:
<?
Include "tag_parser.class.php"// la clase principal

$contenido='<body><title>Pagina de Pablo</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/><meta name="keywords" content="Metatags,Buscador,HTML,Página web" />
</body>Hola <a    href="http://www.mundo.es"  title="cualquier fruta" rel=\'nofollow\'    ><img src="pepe.jpg"/></a>!, loco que <a href="http://www.cruel.com">cruel</a> que sos por <a href="dios.net">Dios</a> ja <p/>

<object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/N9afSH6I3a0&hl=en&fs=1&"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/N9afSH6I3a0&hl=en&fs=1&" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object>

<p><br /><div align="center"><embed pluginspage="http://www.macromedia.com/go/getflashplayer" src="http://www.metacafe.com/fplayer/223037/technology_cooking.swf" width="400" height="345" type="application/x-shockwave-flash" flashvars="altServerURL=http://www.metacafe.com&amp;playerVars=videoTitle=Technology CookingshowStats=yesautoPlay=noblogName=mas tecnoblogURL=http://mastecno.com" wmode="transparent"></embed> </div>

<img style="cursor: pointer;" src="http://1.bp.blogspot.com/_CP8nAQLnf5Y/RpvbtUlyH-I/AAAAAAAAArI/Au7GZ82_I_U/s320/candado2.jpg" alt="" id="BLOGGER_PHOTO_ID_5087901775712886754" border="0" /><!-- no lo parsea! por el style delante -->
<a id="202" title="google uk" href="http://www.google.uk" style=\'color:red\'>Google UK</a>
<a href="pepe.com" >Pepe</a><p/> <IMG   SRC="casa.jpg"   /> '
;

$tags  = new tagParser($contenido);

$tags->parseLinks();

for (
$i=0;$i<$tags->getLinkCount();$i++){
  
$enlace $tags->getLink();
  
$uri $enlace->getUrl();
  
$anchor $enlace->getDiana();
  echo 
"$uri<br/>$anchor<p/>";
}

$tags->parseImages();

for (
$i=0;$i<$tags->getImageCount();$i++){
  
$img $tags->getImage()->getImg();  
  echo 
"$img<br/>";
}

$tags->parseTitle();
echo 
$tags->getTitle();

$tags->parseMetas();
echo 
$tags->getMeta('keywords');

echo 
'<p/>';

$tags->parseVideos();

for (
$i=0;$i<$tags->getVideoCount();$i++){        
  
$video    $tags->getVideo()->getSource();     
  echo 
"$video<br/>";
}  

?>

Espero la encuentren util
__________________
Salu2!

Última edición por Italico76; 13/07/2009 a las 13:25
  #2 (permalink)  
Antiguo 09/07/2009, 12:05
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 11 meses
Puntos: 2135
Respuesta: Clase de parseo en links e imagenes [aporte]

Creo encontrás este aporte muy util: http://www.forosdelweb.com/f18/aport...nas-web-574722

Saludos.
  #3 (permalink)  
Antiguo 09/07/2009, 16:05
Avatar de Italico76  
Fecha de Ingreso: abril-2007
Mensajes: 3.303
Antigüedad: 17 años
Puntos: 292
Respuesta: Clase de parseo en links e imagenes [aporte]

Lo bueno de la que mencionas, es la forma de comunicacion. Muy buena, gracias!
__________________
Salu2!

Última edición por Italico76; 13/07/2009 a las 09:39
  #4 (permalink)  
Antiguo 13/07/2009, 09:40
Avatar de Italico76  
Fecha de Ingreso: abril-2007
Mensajes: 3.303
Antigüedad: 17 años
Puntos: 292
Respuesta: Clase de parseo en links e imagenes [aporte]

si la quieren probar van a necesitar de estas clases tambien:

"links.class.php"
Código PHP:
<? // link class .php

class Img {  // clase img 
  
private $url
  private 
$alt
  private 
$border;    
   
  function 
__construct($url){ 
   
$this->url=$url;   
   
$this->setborder(0);
  } 
  
 function 
addAlt($alt){
   
$this->alt="alt='$alt'";
  }  
  
 function 
setBorder($border){
   
$this->border="border='$border'";
 } 

  function 
getImg(){
   return 
$this->url// aca habia un error (!)
 


 function 
getAlt(){
   return 
$this->alt;
 } 
  
 function 
show (){
   return 
"<img src='$this->url' $this->alt $this->border  />";           
 }    

 function 
__toString (){  
   return (
$this->show()); 
 }  
 


class 
link // super-clase,  antes abstracta (abstract class link)
  
public $url;    // antes protected
  
public $diana
  public 
$title;  // antes protected
  
public $target// antes protected - relacionado con newPage()
    
 
function __construct($url){ 
   
$this->url=$url;        
 }     
  
 function 
addTitle($title){
   
$this->title="title='$title'";   
 }
 
 function 
newPage(){
   
$this->target="target ='_blank'";
  }  
 
 function 
getTarget(){
   return 
$this->target;
 }  
 
 function 
getUrl(){
   return 
$this->url;
 } 
 
 function 
setDiana($diana){ 
   
$this->diana=$diana;
 }

 function 
getDiana(){  
   return 
$this->diana;
 }
 
}

class 
Link2text extends link{    // clase Link a texto
  
private $anchor
    
  function 
__construct($url,$anchor){ 
   
parent::__construct($url); 
   
$this->anchor $anchor
  } 

 function 
setAnchor($anchor){ 
   
parent::setDiana($anchor);
 }

 function 
getAnchor(){ 
   return (
parent::getDiana());
 }
 
 function 
__toString() {  // 'metodo magico'  que genera una salida (me evito ponerle nombre a la funcion porque se ejecuta sola al hacer echo o print)
   
if (isset($this->title)){
     
$title=' '.$this->title;
   }else{     
     
$title=$this->title;
   }     
   return 
"<a href='$this->url'".$title."$this->target>$this->anchor</a>";
 } 
}

class 
Link2graph extends link{  // clase Link a Grafico  
 
  
function __construct($url,$img_url){   // quizas podria acetar un objeto tipo imagen
  
   
parent::__construct($url);    
   
$imagen = new img($img_url);    
   
parent::setDiana($imagen);
  }
  
  function 
addAlt($alt){
   
$this->imagen->addAlt($alt); // uso el metodo add_alt de la clase IMG
  
}  
    
 function 
__toString (){       
   
$img parent::getDiana();
   
$title=$this->title;        
    return 
"<a href='$this->url'  $this->title $this->target >$img</a>";
 }   
}

?>
"video.class.php"
Código PHP:
<? 

class video {  # clase video
   
private $source;  // url
   
private $width;
   private 
$height;    
   private 
$color;    
   private 
$brand// {IMBD: youtube, metacafe, ....}
   
private $id;
   private 
$center;
   
 
  function 
setDefault(){
    
$this->setWidth(400); 
    
$this->setHeight(345);    
    
$this->color[1]='b1b1b1'// anteponer 0x al imprimir
    
$this->color[2]='cfcfcf';
    
$this->center=FALSE;
  } 
 
 function 
setSource($source){
   
$this->source=$source
  }
  
 function 
getSource(){
    return 
$this->source;
  } 
  
 
  function 
__construct($source){ 
  
    
$this->setSource($source);       
    
$this->setDefault();
    
    if (
strstr($source,'youtube')){
      
$this->brand='youtube';
    }else{  
      if (
strstr($source,'metacafe')){
        
$this->brand='metacafe';
      }else{
        echo 
'FORMATO DE VIDEO NO RECONOCIDO';
        break;        
      }       
    }  
  } 
     
  function 
setWidth($width){
    
$this->width =$width;
  } 

  function 
setHeight($height){
    
$this->height $height;
  } 
 
  function 
setColor1($color){
    
$this->color[1] = $color;
  } 
 
  function 
setColor2($color){
    
$this->color[2] = $color;
  }  
   
  function 
setBrand($brand){
    
$this->brand=$brand;
  }
  
  function 
getBrand(){
    return 
$this->brand;
  }
  
  function 
getID() {  
    return 
$this->id// el ID deberia extraerse de SOURCE (!)
  
}    
  
  function 
__toString (){    
  
    switch(
$this->brand){
      case 
'youtube':
        return 
"<object width=\"{$this->width}\" height=\"{$this->height}\"><param name=\"movie\" value=\"{$this->source}&color1=0x{$this->color[1]}&color2=0x{$this->color[1]}&feature=player_embedded&fs=1\"></param><param name=\"allowFullScreen\" value=\"true\"></param><param name=\"allowScriptAccess\" value=\"always\"></param>
<embed src=\"{$this->source}&color1=0x{$this->color[1]}&color2=0x{$this->color[2]}&feature=player_embedded&fs=1\" type=\"application/x-shockwave-flash\" allowfullscreen=\"true\" allowScriptAccess=\"always\" width=\"{$this->width}\" height=\"{$this->height}\"></embed></object>"
;
        break;
      case 
'metacafe':
        return 
"<embed pluginspage=\"http://www.macromedia.com/go/getflashplayer\" src=\"{$this->source}\" width=\"{$this->width}\" height=\"{$this->height}\" type=\"application/x-shockwave-flash\" flashvars=\"altServerURL=http://www.metacafe.com&amp;playerVars=videoTitle=Technology CookingshowStats=yesautoPlay=noblogName=mas tecnoblogURL=http://mastecno.com\" wmode=\"transparent\"></embed>";
      break;
     }     

    
 }     
 
#fin de clase video

class youtube extends video {  #clase hija: youtube
  
  
function __construct($source=""){      
 
    
parent::setSource($source);
    
parent::setDefault();
    
parent::setBrand('youtube');
    
//$this->brand='youtube'; /// por q no funciona en la clase padre ????
    
  
}
  
  function 
setID ($id){ // forma alternativa de indicar de que video se trata
    
$this->id=$id
    
parent::setSource("http://www.youtube.com/v/$id");
  }  
  
  function 
__toString (){ 
    return (
parent::__toString());
  }  
  
}  
# fin de clase 

?>
__________________
Salu2!

Última edición por Italico76; 03/08/2009 a las 16:30
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 09:21.