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

Ayuda con clase de creación de [RSS]

Estas en el tema de Ayuda con clase de creación de [RSS] en el foro de Frameworks y PHP orientado a objetos en Foros del Web. Hola Foro: Tengo la siguiente clase que me permite crear ficheros XML y hacer un RSS bien formado: Código PHP: <? class  rss_generator  {     private  ...
  #1 (permalink)  
Antiguo 02/10/2005, 09:54
Avatar de Reynier  
Fecha de Ingreso: noviembre-2002
Ubicación: Por ahí en algún sitio
Mensajes: 1.844
Antigüedad: 21 años, 5 meses
Puntos: 1
Ayuda con clase de creación de [RSS]

Hola Foro:
Tengo la siguiente clase que me permite crear ficheros XML y hacer un RSS bien formado:
Código PHP:
<?
class rss_generator {

    private 
$_encoding="UTF-8";
    private 
$_title="";
    private 
$_language="en-us";
    private 
$_description="";
    private 
$_link="";
    private 
$_generator="Portal Joven Club Granma RSS Generator";
    private 
$_version="2.0";
    private 
$_category "";
    private 
$_author "";

    public function 
__construct($title) {
        
$this->_title=$title;
    }
    public function 
__get($name) {
        if (
$name=='encoding')        return $this->_encoding;
        if (
$name=='title')            return $this->_title;
        if (
$name=='language')        return $this->_language;
        if (
$name=='description')    return $this->_description;
        if (
$name=='generator')        return $this->_generator;
        if (
$name=='link')            return $this->_link;
        if (
$name=='category')        return $this->_category;
        if (
$name=='author')        return $this->_author;
    }
    public function 
__set($name,$value) {
        if (
$name=='encoding')        $this->_encoding    stripslashes($value);
        if (
$name=='title')            $this->_title        stripslashes($value);
        if (
$name=='language')        $this->_language    stripslashes($value);
        if (
$name=='description')    $this->_description    stripslashes($value);
        if (
$name=='generator')        $this->_generator    stripslashes($value);
        if (
$name=='link')            $this->_link         stripslashes($value);
        if (
$name=='category')        $this->_category     stripslashes($value);
        if (
$name=='author')        $this->_author         stripslashes($value);
    }

    
/**
    Make an xml document of the rss stream
    @param: items: n row of associative array with theses field:
            'title': title of the item
            'description': short description of the item
            'pubData': publication timestamp of the item
            'link': url to show the item
    @result: xml document of rss stream
    **/
    
public function MakeRSS($items) {
        
$res="";
        
$res.="<?xml version=\"1.0\" encoding=\"".$this->_encoding."\"?>\n";
        
$res.="<rss version=\"2.0\">\n";
        
$res.="\t<channel>\n";
        
$res.="\t\t<title><![CDATA[".$this->_title."]]></title>\n";
        
$res.="\t\t<description><![CDATA[".$this->_description."]]></description>\n";
        
$res.="\t\t<language>".$this->_language."</language>\n";
        
$res.="\t\t<generator>".$this->_generator."</generator>\n";

        foreach(
$items as $item) {
            
$res.="\t\t<item>\n";
            
$res.="\t\t\t<title><![CDATA[".stripslashes($item["title"])."]]></title>\n";
            
$res.="\t\t\t<description><![CDATA[".stripslashes($item["description"])."]]></description>\n";
            
            if (!empty(
$item["pubDate"]))
                
$res.="\t\t\t<pubDate>".date("r"stripslashes($item["pubDate"]))."</pubDate>\n";
            if (!empty(
$item["link"]))
                
$res.="\t\t\t<link>".stripslashes($item["link"])."</link>\n";
            if (!empty(
$item["author"]))
                
$res.="\t\t\t<author>".stripslashes($item["author"])."</author>\n";
            
$res.="\t\t</item>\n";
        }
        
$res.="\t</channel>\n";
        
$res.="</rss>\n";
        return 
$res;
    }
}
?>
la clase tiene algunas modificaciones que yo he hecho. Entonces como pueden ver para generar el fichero XML es necesario llamar la funcion MakeXML y pasarle un arreglo asociativo de contenido. Entonces el arreglo lo obtengo en este fichero:
Código PHP:
<?
setlocale
(LC_ALL'esp_ESP');
include_once(
'../config.inc.php');
include_once(
'../includes/class_rss_generator.inc.php');
include_once(
'../includes/adodb/adodb.inc.php');
include_once(
'../includes/dBug.php');

# Inicializamos AdoDB
$db ADONewConnection($tipo);
$db->PConnect($servidor,$usuario,$passwd,$base_de_datos);

$mod = isset($_GET['mod'])?$_GET['mod']:null;
$opt = isset($_GET['opt'])?$_GET['opt']:null;

$contar_noticias $db->Execute("SELECT COUNT(IDN) AS cantidad FROM noticia");
$rscantidad $contar_noticias->fetchRow();

$rss = new rss_generator('Portal de los Joven Club de Computación y Electronica de Granma');

if ( 
$rscantidad[0] > ){
        
$noticias = array();
        
$fecha_noticias $db->SQLDate('d M Y - h:i:s A','FechaN');
        
$noticia $db->Execute("SELECT IDN, IDC, $fecha_noticias, TituloN, DescN, AutorN FROM noticia ORDER BY FechaN DESC");
        while(
$rs $noticia->fetchRow()){
            
$noticias[] = $rs;
        }
}

new 
dBug($noticias);
$rss->MakeRSS($noticias);
?>
pero cuando voy a llamar a la funcion MakeXML me da este error
Cita:
Notice: Undefined index: title in d:\phprojects\includes\class_rss_generator.inc.php on line 59

Notice: Undefined index: description in d:\phprojects\includes\class_rss_generator.inc.php on line 60

Notice: Undefined index: title in d:\phprojects\includes\class_rss_generator.inc.php on line 59

Notice: Undefined index: description in d:\phprojects\includes\class_rss_generator.inc.php on line 60

Notice: Undefined index: title in d:\phprojects\includes\class_rss_generator.inc.php on line 59

Notice: Undefined index: description in d:\phprojects\includes\class_rss_generator.inc.php on line 60
Alguna ayuda? El arreglo $noticias tiene valores porque los he debugeado.

Salu2
__________________
Ing. Reynier Pérez Mira
  #2 (permalink)  
Antiguo 02/10/2005, 17:10
Avatar de richardinj  
Fecha de Ingreso: enero-2005
Ubicación: Ciber Espacio
Mensajes: 2.180
Antigüedad: 19 años, 3 meses
Puntos: 11
El error dice que title y description no estan definidos .. eso sucede porque:

1. no existe esa variable.
  #3 (permalink)  
Antiguo 02/10/2005, 18:20
Avatar de DINASEN  
Fecha de Ingreso: marzo-2003
Mensajes: 997
Antigüedad: 21 años, 1 mes
Puntos: 1
hola puedes dejar el link de donde te bajaste ese script la verdad es qu eme vendria bien tenerlo

Gracias

Un Saludo
  #4 (permalink)  
Antiguo 02/10/2005, 20:49
Avatar de Reynier  
Fecha de Ingreso: noviembre-2002
Ubicación: Por ahí en algún sitio
Mensajes: 1.844
Antigüedad: 21 años, 5 meses
Puntos: 1
Hola

richardinj) La variable "title" segun tengo entendido debe estar en el arreglo y esta contenida.

DINASEN) Lo baje de www.phpclasses.org

Salu2 a ambos
__________________
Ing. Reynier Pérez Mira
  #5 (permalink)  
Antiguo 03/10/2005, 03:41
Avatar de jam1138
/** @package Moderador */
 
Fecha de Ingreso: julio-2004
Ubicación: sèveR led onieR lE
Mensajes: 9.368
Antigüedad: 19 años, 9 meses
Puntos: 102
... haber, solo para aclarar... cuando haces:
Código PHP:
if ( $rscantidad[0] > ){ 
... ¿qué haces? (, válgase la redundancia). Por la comparación pareciera que solo verificas que haya habido resultados en la consulta... pero ¿una matriz? . El proceso anterior da a entender que lo que representa dicha matriz son los resultados mismos:
Código PHP:
$rscantidad $contar_noticias->fetchRow();

// lo "ratifica" lo que haces después:
        
while($rs $noticia->fetchRow()){ 
            
$noticias[] = $rs
        } 
... solo adivinando e intuyendo , no muestras esa parte... pero si estoy en lo correcto, entonces la comparación debería ser algo como:
Código PHP:
if ( count($rscantidad) > ){
// quizá...
if ($rscantidad != 'NULL' ){
// e incluso
if/mysql_num_rows($rscantidad) > ){ 
¿no? ... como que algo "no me late" por ahí... . Sácame de la duda .

... ahora ¿por qué no mandas a imprimir la matriz antes de ejecutar la función MakeRSS()??, posiblemente ahí se vea el problema:
Código PHP:
new dBug($noticias); 
// $rss->MakeRSS($noticias); 
echo "<pre>";
   
print_r($noticias);
echo 
"</pre>";
?> 
Haber qué resulta... Suerte!
__________________
٩(͡๏̯͡๏)۶
» Cómo hacer preguntas de manera inteligente «

"100 años después, la revolución no es con armas, es intelectual y digital"

Última edición por jam1138; 03/10/2005 a las 03:46
  #6 (permalink)  
Antiguo 03/10/2005, 07:03
Avatar de Reynier  
Fecha de Ingreso: noviembre-2002
Ubicación: Por ahí en algún sitio
Mensajes: 1.844
Antigüedad: 21 años, 5 meses
Puntos: 1
Disculpas

Hola jam1138:
Te explico.
Código PHP:
if ( $rscantidad[0] > 
esto lo que hace es veficar si existen o no noticias en la tabla. Entonces si te fijas en mi código incluyo un fichero llamado dBug.php que se encarga de imprimirme los arreglos de una forma amigable. Fijate que la instancion y le paso como parametro el arreglo.
Código PHP:
include_once('../includes/dBug.php'); 
new 
dBug($noticias); 
Me he ido por otra via. O sea esta:
Código PHP:
# RSS File
$res="";
$res.="<?xml version="1.0\" encoding=\"UTF-8\"?>\n";
$res.="<rss version=\"2.0\">\n";
$res.="\t<channel>\n";
$res.="\t\t<title><![CDATA[RSS Portal de los Joven Club de Computaci&oacute;n y Electr&oacute;nica de Granma]]></title>\n";
$res.="\t\t<description><![CDATA[RSS Portal de los Joven Club de Computaci&oacute;n y Electr&oacute;nica de Granma]]></description>\n";
$res.="\t\t<language>es-es</language>\n";
$res.="\t\t<generator>RSS Portal JClub Granma</generator>\n";

if ( 
$rscantidad[0] > ){
    
$fecha_noticias $db->SQLDate('d M Y - h:i:s A','FechaN');
    
$noticia $db->Execute("SELECT IDN, IDC, $fecha_noticias, TituloN, DescN, AutorN FROM noticia WHERE (NACtiva<>0) ORDER BY FechaN DESC");
    while(
$rs $noticia->fetchRow()){
        
$res.="\t\t<item>\n";
        
$res.="\t\t\t<title><![CDATA[".stripslashes($rs['TituloN'])."]]></title>\n";
        
$res.="\t\t\t<description><![CDATA[".stripslashes($rs['DescN'])."]]></description>\n";
        
$res.="\t\t\t<pubDate>".stripslashes($fecha_noticias)."</pubDate>\n";
        
$res.="\t\t\t<link>".stripslashes($PageAdress."&amp;IDC=".$rs['IDC']."&amp;IDN=".$rs['IDN'])."</link>\n";
        
$res.="\t\t\t<author>".stripslashes($rs["AutorN"])."</author>\n";
        
$res.="\t\t</item>\n";
    }
}

$res.="\t</channel>\n";
$res.="</rss>\n";

$actual date("Ymd");

$handler  fopen("noticias-".$actual.".xml",'w+');
if(!
fputs($handler$res)) {
    echo 
"No se pudo crear el Rss";
}
fclose($handler);
pero ahora me da error en el fichero XML pues me dice que esta mal formado.

Salu2
__________________
Ing. Reynier Pérez Mira
  #7 (permalink)  
Antiguo 26/10/2005, 23:28
Avatar de jam1138
/** @package Moderador */
 
Fecha de Ingreso: julio-2004
Ubicación: sèveR led onieR lE
Mensajes: 9.368
Antigüedad: 19 años, 9 meses
Puntos: 102
Cita:
esto lo que hace es veficar si existen o no noticias en la tabla.
Una matriz??. No se le ve mucho "sentido" la forma en que manejas tus variables... Cuál es el contenido de dicha matriz?.

Cita:
si te fijas en mi código incluyo un fichero llamado dBug.php que se encarga de imprimirme los arreglos de una forma amigable.
Lo mismo... si lo imprimes ¿cuál es el resultado?. ¿hiciste lo que te mecioné --imprimir la matriz directamente--?; ¿cuál fue el resultado?.

Cita:
pero ahora me da error en el fichero XML pues me dice que esta mal formado.
... problema del XML.... vámos! lo mismo: ¿cuál fue tu archivo XML obtenido?, ¿el mensaje te lo dió el navegador?...

Saludos!
__________________
٩(͡๏̯͡๏)۶
» Cómo hacer preguntas de manera inteligente «

"100 años después, la revolución no es con armas, es intelectual y digital"
  #8 (permalink)  
Antiguo 27/10/2005, 06:24
Avatar de Reynier  
Fecha de Ingreso: noviembre-2002
Ubicación: Por ahí en algún sitio
Mensajes: 1.844
Antigüedad: 21 años, 5 meses
Puntos: 1
Gracias

Muchas gracias pero ya lo resolví de otra manera. Ahora el problema esta en dar estilo a ese archivo XML. Tengo entendido que ello se puede hacer con CSS y con XSL. De la primera se algo pero de la segunda nada. Alguna idea al respecto o ayuda??
Salu2 y gracias
__________________
Ing. Reynier Pérez Mira
  #9 (permalink)  
Antiguo 27/10/2005, 07:52
O_O
 
Fecha de Ingreso: enero-2002
Ubicación: Santiago - Chile
Mensajes: 34.417
Antigüedad: 22 años, 3 meses
Puntos: 129
Cita:
Iniciado por Reynier
Muchas gracias pero ya lo resolví de otra manera. Ahora el problema esta en dar estilo a ese archivo XML. Tengo entendido que ello se puede hacer con CSS y con XSL. De la primera se algo pero de la segunda nada. Alguna idea al respecto o ayuda??
Salu2 y gracias
En el foro de XML te podrían orientar ...

Un saludo,
  #10 (permalink)  
Antiguo 27/10/2005, 15:46
Avatar de jam1138
/** @package Moderador */
 
Fecha de Ingreso: julio-2004
Ubicación: sèveR led onieR lE
Mensajes: 9.368
Antigüedad: 19 años, 9 meses
Puntos: 102
Cita:
Muchas gracias pero ya lo resolví de otra manera.
Y de qué manera??. Gracias por colaborar con el foro...
__________________
٩(͡๏̯͡๏)۶
» Cómo hacer preguntas de manera inteligente «

"100 años después, la revolución no es con armas, es intelectual y digital"
  #11 (permalink)  
Antiguo 27/10/2005, 22:34
Avatar de Reynier  
Fecha de Ingreso: noviembre-2002
Ubicación: Por ahí en algún sitio
Mensajes: 1.844
Antigüedad: 21 años, 5 meses
Puntos: 1
Mis disculpas

Disculpen sino deje el código. Estaba un poco apurado .... :-p pero bueno aquí esta:
Código PHP:
if ( $opt == "crear" ) {
    $pubDate = date("D M j G:i:s T Y");
    $contar_noticias = $db->Execute("SELECT COUNT(IDN) AS cantidad FROM noticia");
    $rscantidad      = $contar_noticias->fetchRow();
    
    # RSS File
    $res = "";
    $res.= "<?xml version="1.0\" encoding=\"UTF-8\"?>\n";
    
$res.= "<rss version=\"2.0\">\n";
    
$res.= "\t<channel>\n";
    
$res.= "\t\t<title><![CDATA[RSS Portal de los JCCE de Granma]]></title>\n";
    
$res.= "\t\t<description><![CDATA[RSS Portal de los JCCE de Granma]]></description>\n";
    
$res.= "\t\t<language>es-es</language>\n";
    
$res.= "\t\t<generator>RSS Portal JClub Granma</generator>\n";
    
$res.= "\t\t<link>http://www.jovenclub.cu/grm/tinogrm.rss</link><description>RSS Portal de los JCCE de Granma></description><language>es-ES</language><pubDate>"$pubDate ."</pubDate>\n";
    
$res.= "<image><title>RSS Portal de los JCCE de Granma</title><url>http://www.jovenclub.cu/grm/tinogrmrss.png</url><link>http://www.jovenclub.cu/grm/tinogrm.rss</link></image>\n";
    
    
    if (
$rscantidad[0] > 0) {
        
$fecha_noticias$db->SQLDate('d M Y - h:i:s A''FechaN');
        
$noticia       $db->Execute("SELECT IDN, IDC, $fecha_noticias, TituloN, DescN,ImgN, AutorN FROM noticia WHERE (NACtiva<>0) ORDER BY FechaN DESC");
        while ( 
$rs $noticia->fetchRow() ) {
            
$res.="\t\t<item>\n";
            
$res.="\t\t\t<title><![CDATA[" htmlspecialchars($rs['TituloN']) . "]]></title>\n";
            
$res.="\t\t\t<description><![CDATA[ <p><b> ";
            if (
$rs['ImgN'] !=""){
                
$res.="<img src=http://www.jovenclub.cu/grm/themes/images/noticias/"$rs['ImgN'] ." align=left >";
            }else{
                
$res.="<![CDATA[" htmlspecialchars$rs['DescN']) . "]]></description>\n";
            }
            
$res.="\t\t\t<pubDate>" $fecha_noticias "</pubDate>\n";
            
$res.="\t\t\t<link>" $PageAdress "&amp;IDC=" $rs['IDC'] . "&amp;IDN=" $rs['IDN'] . "</link>\n";
            
$res.="\t\t\t<author>" htmlspecialchars$rs["AutorN"] ) . "</author>\n";
            
$res.="\t\t</item>\n";
        }
    }
    
$res.= "\t\t</channel>\n";
    
$res.= "\t\t</rss>\n";
    
    
$tpl->assign('file''tinogrm.xml');
    
$actual =date("Ymd");
    
$handler=fopen("../tinogrm.xml"'w+');
    if (!
fputs($handler$res)) {
        
$tpl->assign("msg","No se pudo crear el RSS");
    } else {
        
$tpl->assign("msg","El fichero RSS ha sido creado satisfactoriamente");
    }
    
fclose($handler);
    
$file "tinogrm.xml";
    
$tpl->assign('file'$file);
}
Salu2
__________________
Ing. Reynier Pérez Mira
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 22:04.