Este es el primer tutorial que escribo en Cristalab. La creación de un feed RSS con MySQL y PHP. Si apenas estas comenzando te recomiendo que leas Cómo crear tu propio feed RSS manualmente, que aborda el tema del formato RSS a profundidad.
De todos modos si tienes idea de lo que es RSS adelante con este tip. Cabe mencionar que mis conocimientos son algos básicos en algunas cosas, sin embargo lo que se y he aprendiendo en esta gran comunidad lo comparto con ustedes, el ejemplo que les pondré a continuación esta basado en un ejemplo que desarrolló Alejandro Suazo por el año 2005. Este es uno de los ejemplos más difundidos de como realizar un Feed RSS, aunque contiene algunos errores de escritura y sintaxis, todos o la mayoría de esos errores los arregle y el ejemplo ya esta funcional.
Entendamos qué es RSS
El feed RSS es un sencillo formato de datos que es utilizado para redifundir contenidos a suscriptores de un sitio web. El formato permite distribuir contenido sin necesidad de un navegador, utilizando un software diseñado para leer estos contenidos RSS (agregador). A pesar de eso, es posible utilizar el mismo navegador para ver los contenidos RSS. Las últimas versiones de los principales navegadores permiten leer los RSS sin necesidad de software adicional.
Existen 3 formatos de RSS :
- RSS (0.91) Rich Site Summary
- RSS (0.0 y 1.0) RDF Site Summary
- RSS (2.0) Really Simple Sindication
Para mas información sobre el RSS, pueden visitar la página de Wikipedia.
¿Cómo creamos el documento RSS?
Es muy sencillo crear un documento RSS ya que en si es un archivo XML.
- El archivo debe comenzar indicando la versión de XML y la codificación. En este caso utilizo codificación “iso-8859-1“, para caracteres latinos (ñ o tildes).
- A continuacíon añadimos las etiquetas de apertura y cierre <rss></rss> e indicamos la versión del tipo de documento y después tendremos que crear un canal donde vamos a publicar nuestros contenidos .
- Los tres elementos siguientes son obligatorios en todo feed RSS e identifican a nuestro feed y a nuestro sitio web.
- En primer lugar indicaremos el título de nuestro sitio, a continuación especificamos la url donde se puede encontrar nuestra feed RSS y por último una breve descripción de lo que se puede encontrar en nuestro sitio.
- Después de las tres líneas anteriores añadiremos un elemento item por cada entrada que vayamos a incluir en nuestro feed.
Cada item consta de tres elementos obligatorios:
- title. Que contiene el título del artículo.
- link. Que contiene el enlace directo a la versión completa del artículo. De esta forma los suscriptores interesados podrán leer el artículo completo.
- description. Que contiene un resúmen de lo que encontraremos en el artículo.
Y varios elementos opcionales, de los cuales utilizo únicamente dos:
- pubDate. Que indica la fecha de publicación del artículo.
- category. Que contiene el nombre de la categoría al que pertenece el artículo.
Ejemplo:
Código :
<?xml version=”1.0″ encoding=”iso-8859-1″ ?> <rss version=”2.0″> <channel> <item> <title>El título de mi artículo 1</title> <link>http://www.mipagina.com/noticia1.html</link> <description>Resúmen de la noticia</description> <pubDate>Lun, 14 Dic 2009 11:56:26 GMT</pubDate> <category>Categoría</category> </item> </channel> </rss>
Ya que tenemos más o menos claro lo que es RSS podemos poner manos a la obra y empezar a crear nuestro feed de noticias para nuestra página web.
Crear la base de datos
El primer paso será crear la base de datos y añadir los datos. Si nuestra página ya utiliza algún tipo de base de datos para guardar los artículos no será necesario crear otra base de datos ni tampoco hacer cambios, solamente necesitaras adecuar el script a tus necesidades.
- id_noticia – no es obligatorio pero a mi en lo particular me gusta manejar por números los registros
- autor – nombre del autor que publica las noticias
- titulo – título que veremos en el RSS
- categoria –categoría o tag del articulo (nos permitirá organizar mejor)
- fecha – fecha del articulo para la organización (los más nuevos son los primeros)
- noticia – nuestros artículos se guardaran en este campo
Esta sería la estructura SQL para facilitar un poco el como funciona este ejemplo:
Código :
CREATE TABLE IF NOT EXISTS `noticias` ( `id_noticia` int(4) NOT NULL auto_increment, `autor` varchar(255) default NULL, `titulo` varchar(255) default NULL, `categoria` varchar(255) default NULL, `fecha` date NOT NULL, `noticia` text, KEY `id_noticia` (`id_noticia`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
Para utilizar los datos genere un archivo llamado conexion donde almacenamos la información de nuestra BD.
Archivo: conexion.php
Código :
<?php function Conectarse() { //conectamos a la base if (!($link=mysql_connect(“servidor”,”usuario”,”contraseña”))) { echo “Error conectando a la base de datos.”; exit(); } //Seleccionamos la base if (!mysql_select_db(“base_de_datos”,$link)) { echo “Error seleccionando la base de datos.”; exit(); } return $link; } ?>
Ya que tenemos nuestra tabla en nuestra base de datos, vamos a empezar a ver el script que nos genera nuestro Feed de noticias.
Archivo: rss.php
Código :
<?php header('Content-type: text/xml; charset="iso-8859-1"', true); echo '<?xml version="1.0" encoding="iso-8859-1"?>'; //Aquí la conexión o archvio de conexión a la base de datos include ("noticias/conexion.php"); $link=Conectarse(); //Hacemos la consulta y la ordenamos por post para mostrar siempre el último $resultado=mysql_query("select * from noticias order by id_noticia Desc",$link); //"Cortaremos" el artículo en 300 caracteres para nuestra descripción $descripcion=substr($row[noticia],0,300)."..."; // Y generamos nuestro documento echo '<rss version="2.0">'; echo '<channel> <title>Colegio Atid</title> <link>http://www.atid.edu.mx/</link> <language>es-CL</language> <description>Noticias del Colegio Atid</description> <generator>Randy Espiritu</generator>'; while($row = mysql_fetch_array($resultado)){ echo '<item> <title>'.$row[titulo].'</title> <link>http://www.atid.edu.mx/comunidad/news.php?id='.$row[id_noticia].'</link> <pubDate>'.$row[fecha].'</pubDate> <category>'.$row[categoria].'</category> <description><![CDATA['.$row[noticia].']]></description> </item>'; } echo' </channel> </rss>'; ?>
Podemos ver que la estructura del documento es sencilla y hasta repetitiva. Básicamente podemos dividirlo en dos: <channel> e <item> en donde <channel> contiene a <item> . El primer bloque antes de <item> se llena con los datos de nuestro blog o web, luego bajo la etiqueta mencionada van los datos del post o noticia a mostrar.
Una práctica sana es utilizar la etiqueta <content:encoded> , para proporcionar la información que contiene nuestro artículo completo en vez de <description> ¿por qué?, porque los sistemas de recopilación de feeds o lectura de estos, leen la etiqueta <description> para darle al lector un resumen de lo que trata el post. Lo menciono, porque hay sistemas de blog's que usan <description> para generar la información del artículo completo y no dan la opción de ver si queremos o no seguir leyendo lo que nos ofrecen, aparte de ocupar espacio. Para estas dos etiquetas usamos la sección XML <![CDATA[ ]]> (character data), básicamente para que el XML no interprete ciertos caracteres como propios de su lenguaje y trate de ejecutarlos.
Para hacer accesible tu canal RSS debes de poner un enlace a tu archivo desde tu página web.
Bastará con que insertes una línea como la que se muestra a continuación en el código HTML de la página en la que quieras que aparezca el enlace:
Código :
<a type="application/rss+xml" href="rss.php"><img src="icono_rss.gif"></a>
También debemos incluir lo siguiente entre las etiquetas <head> de nuestras páginas:
Código :
<link rel="alternate" type="application/rss+xml" title="My RSS Feed" href="rss.php" />
De esta forma los navegadores (al menos los más utilizados, Firefox e Internet Explorer, en sus últimas versiones) detectarán que nuestro sitio tiene un feed RSS 2.0 y mostrarán un icono a los visitantes de nuestro sitio en la barra de direcciones para suscribirse directamente, en algunos navegadores viejos no se visualiza bien los feed, o también puede que tu servidor no reconozca este tipo de archivos.
Espero les sirva este tip, se que hay muchas formas de hacerlo, pero a mi en lo particular esta forma me a funcionado, si alguíen quiere hacerle mejoras seran bien recibidas.
Saludos
¿Sabes SQL? ¿No-SQL? Aprende MySQL, PostgreSQL, MongoDB, Redis y más con el Curso Profesional de Bases de Datos que empieza el martes, en vivo.
Por luco el 21 de Marzo de 2011
Por flashreloco el 23 de Marzo de 2011
Por TeamViews el 14 de Julio de 2011
Número de línea 10, columna 1:
<?xml version="1.0" encoding="iso-8859-1"?><br />
^
Por piven el 10 de Noviembre de 2011
Por Ruben el 01 de Febrero de 2012
Por Gon el 19 de Marzo de 2012
Por Jordi el 27 de Diciembre de 2012
Tengo una pregunta. Estoy haciendo una web con html y css, pero de momento no usará bases de datos ni php. Sin embargo me gustaría saber si es posible utilizar la posibilidad que tengo con el servicio de alojamiento (hosting) que tengo contratado de crear bases de datos y utilizarlas para casos como este de crear un feed, paginación o similar.
Puedo crear bases de datos, con nombre de usuario, contraseña y nombre de host, pero no puedo acceder al código de ellas. Las utilizo para guardar el CMS de wordpress, pero en esta ocasión quiero no quiero usar el wordpress y me interesa crear una web para manejarla desde Dreamweaver.
Así, la duda que tengo es si este mismo tutorial me servirá, aunque no haya creado nada con php antes para los artículos del blog (de momento lo haré manual). Y si es posible mezclar archivos php con html en el site.
Gracias y saludos
Por Miguel Geek el 27 de Febrero de 2013
Un saludo!
Por anthoe21 el 20 de Septiembre de 2013
Por Fernando el 18 de Noviembre de 2013
Por Oscar el 07 de Enero de 2014
Por miguel el 20 de Noviembre de 2014
gracias por tu tiempo y si tienes alguna recomendación sobre el feedburner.
Por José el 31 de Enero de 2018
classroom rental space
training rrom rental in singapore
training rooms in singapore
seminar room rental in singapore
indoor team building activities
corporate team building games singapore
team bonding in singapore
team building activities singapore
team building games singapore
10 soft skills you need
administrative office procedures
administrative support courses
adult learning mental skills
adult learning physical skills
anger management courses in singapore
appreciative inquiry courses
archiving and records management
assertiveness and self confidence
attention management courses
basic bookkeeping courses
being a likeable boss
body language basics courses
budgets and financial reports
business acumen courses
business ethics courses
business etiquette courses in singapore
business succession planning courses
business writing courses in singapore
call center training courses
change management courses in singapore
coaching and mentoring courses
coaching sales people courses
collaborative business writing
communication strategies courses
conducting annual employee reviews
conflict resolution courses
contact center training courses
contract management courses in singapore
creating a great webinar
creative problem solving courses
crisis management courses
critical thinking courses in singapore
customer service courses in singapore
customer support courses
cyber security courses in singapore
delivering constructive criticism
developing a lunch and learn
developing corporate behavior
developing creativity courses
developing new managers
digital citizenship courses
emotional intelligence courses
employee motivation courses
employee on boarding courses
employee recognition courses
employee recruitment courses
employee termination processes
entrepreneurship courses in singapore
event planning courses in singapore
executive and personal assistants
facilitation skills courses
generation gaps courses
goal setting and getting things done
handling a difficult customer
health and wellness at work courses
high performance teams inside the company
high performance teams remote work force
hiring strategies courses
human resource management courses in singapore
improving mindfulness
improving self awareness
increasing your happiness
internet marketing fundamentals courses
interpersonal skills courses
job search skills courses
knowledge management courses in singapore
leadership and influence courses
lean process and six sigma
life coaching essentials courses
manager management courses
managing personal finances courses
managing work place anxiety
marketing basics courses
measuring results from training
media and public relations courses
meeting management courses
middle manager courses
millennial on boarding courses
m learning essentials
motivating your sales team
multi level marketing courses
negotiation skills courses
networking outside the company
networking within the company
office politics for managers
organizational skills courses
overcoming sales objections
performance management courses
personal branding courses in singapore
personal productivity courses
presentation skills courses in singapore
project management courses in singapore
proposal writing courses
prospecting and lead generation
public speaking courses in singapore
risk assessment and management courses
safety in the work place courses
sales fundamentals courses
sales training courses in singapore
servant leadership courses
it courses in singapore
microsoft training singapore
corporate training in singapore
corporate sgx
social intelligence courses
social learning courses
social media in the work place
social media marketing courses in singapore
soft skills courses in singapore
stress management courses in singapore
supervising others
supply chain management courses
taking initiative courses
talent management courses
team building for managers
team building through chemistry
teamwork and team building
telephone etiquette courses
telework and telecommuting
time management courses in singapore
trade show staff training
train the trainer courses
virtual team building and management
women in leadership courses
work life balance courses in singapore
work place diversity courses
work place harassment courses
work place violence courses
sancy suraj
sancy suraj
sancy suraj
sancy suraj
sancy suraj
sancy suraj
sancy suraj
sancy suraj
[url=https://books.google.com.sg/books?id=1QykBQAAQBAJ&pg=PT362&lpg=PT362&dq=%22sancy+suraj+singh%22&source=bl&ots=E86QDyrLG2&sig=H-6a_YH-kTWaZWTfPSr1xfm4BOs&hl=en&sa=X&ved=0ahUKEwi3_56hhubVAhWJLo8KHcxTBxQ4ChDoAQgjMAA#v=onepage&q =% 22sancy% 20suraj% 20singh% 22 & f = false]sancy suraj[/url]
sancy suraj
longest colour sequence memorised
sancy suraj
longest colour sequence memorised
memory training course
memory training course
memory training course
memory training course
memory training course
memory training course
memory training course
memory training course
memory training course
memory training course
memory training course
memory training course
memory training course
memory training course
memory training course
memory training course
memory training course
memory training course
lunch talks
lunch talks
memory training course
memory training course
cabin crew
online memory course
memory training course
memory training course
memory training course
memory training course
memory training course
speed reading
tuition
tuition
tuition
tuition
tuition
tuition
tuition
tuition
tuition
tuition
geography tuition for secondary school students in singapore
geography tuition for secondary school students singapore
geography tuition for secondary school students singapore
geography tuition for secondary school students singapore
geography tuition for secondary school students singapore
secondary geography tuition in singapore
history tuition for secondary school students in singapore
social studies tuition for secondary school students in singapore
psle english tuition in singapore
psle science tuition in singapore
secondary 1 chemistry tuition in singapore
secondary 1 physics tuition in singapore
school holiday workshops courses for students in singapore
school holidays activitie in singapore
school holidays activitie in singapore
[url=http://umonictuitionadvantage.com/2017-november-school-holidays-activities-programmes-workshop-courses-camps-for- students-kids-in-singapore/]school holidays activitie in singapore[/url]
school holidays activitie in singapore
study skills
study skills
study skills workshops course in singapore
study skills workshops course in singapore
speed reading
speed reading
tuition
tuition
tuition
tuition
tuition
tuition
tuition
tuition
tuition
tuition
tuition
tuition
tuition
tuition
tuition
tuition[
tuition[
tuition[
tuition[
tuition[
tuition[
tuition[
tuition[
student courses
corporate training
corporate training
corporate training
corporate training
corporate training
corporate training
corporate training
corporate training
corporate training
corporate training
corporate training
corporate training
corporate training
corporate training
corporate training
corporate training
corporate training
corporate training
corporate training
corporate training
corporate training
corporate training
lunch talk
lunch talk
lunch talk
lunch talk
lunch talk
lunch talk
lunch talk
lunch talk
lunch talk
lunch talk
lunch talk
lunch talk
corporate lunch talk
corporate lunch talk
corporate lunch talk
corporate lunch talk
corporate lunch talk
corporate lunch talk
corporate lunch talk
corporate lunch talk
corporate lunch talk
corporate lunch talk
corporate lunch talk
corporate lunch talk
corporate lunch talk
corporate lunch talk
team building
team building ideas
team building activities
unique team building
team building
corporate training in singapore
corporate training courses
corporate training courses
corporate training courses
corporate training courses
corporate health talk
corporate health talk
corporate health talk
lunch and learn talk
workplace lunch and learn
corporate training companies in singapore
training companies in singapore
emcee
emcee
health talks
soft skills training course
corporate training providers
professional development courses
training and development courses
short courses in singapore
corporate training courses in singapore
corporate training courses
corporate training in singapore
school holiday workshops courses for students in singapore
business students memory course in singapore
business students memory improvement workshop in singapore
memory improvement course for business students
memory improvement course for business students
business students memory improvement course
business students memory course in singapore
corporate health talks singapore
corporate health talks in singapore
corporate health talk singapore
corporate health talk in singapore
corporate health talks singapore
corporate health talks singapore
finance students memory training course in singapore
finance students memory training course in singapore
finance students memory training course in singapore
memory training courses for finance students in singapore
memory training courses for finance students in singapore
memory improvement courses for finance students in singapore
pinnacle minds
memory course
study skills
speed reading
memory training
school holiday
lunch and learn
march school holidays workshops
march school holidays workshops
march school holidays workshops
march school holidays workshops
march school holidays workshops
june school holidays workshops
june school holidays workshops
june school holidays workshops
june school holidays workshops
september 2018 school holidays workshops
september 2018 school holidays workshops
september 2018 school holidays workshops
september 2018 school holidays workshops
november 2018 school holidays workshops
november 2018 school holidays workshops
november 2018 school holidays workshops
november 2018 school holidays workshops
december 2018 school holidays workshops
december 2018 school holidays workshops
december 2018 school holidays workshops
december 2018 school holidays workshops
top 10 soft skills you need training course
administrative office procedures training course
administrative support training course
anger management training course
appreciative inquiry training course
archiving and records management training course
archiving and records management training course
self confidence and assertiveness training course
improving your attention management training course
bacis bookkeeping training course
being a likeable boss training course
body language training course
budgets and-financial reports training course
business acumen training course
business ethics training course
business etiquette training course
business succession planning training course
business writing training course
call centre training course
change management training course
civility in the workplace training course
coaching and mentoring training course
coaching salespeople training course
collaborative business writing training course
communication strategies training course
conducting annual employee reviews training course
conflict resolution training course
contact centre training course
contract management training course
creating a great webinar training course
creative problem solving training course
crisis management training course
critical thinking training course
customer service training course
customer support training course
cyber security training course
delivering constructive criticism training course
developing lunch and learn training course
developing corporate behavior training course
developing creativity training course
developing new managers training course
digital citizenship training course
emotional intelligence training course
employee motivation training course
employee onboarding training course
employee recognition training course
employee recruitment training course
employee termination processes training course
entrepreneurship training course
event planning training course
executive and personal assistants training course
facilitation skills training course
generation gaps training course
goal setting and getting things done training course
handling a difficult customer training course
health and wellness at work training course
high performance teams inside the company training course
high performance teams remote workforce training course
hiring strategies training course
human resource management training course
improving mindfulness training course
improving self awareness training course
internet marketing fundamentals training course
interpersonal skills training course
job search skills training course
knowledge management training course
leadership and influence training course
lean process and six sigma training course
life coaching essentials training course
manager management training course
managing personal finances training course
managing workplace anxiety training course
marketing basics training course
measuring results from training course
media and public relations training course
meeting management training course
middle manager training course
millennial onboarding training course
mlearning essentials training course
motivating your sales team training course
negotiation skills training course
networking outside the company training course
networking within the company training course
office politics for managers training course
organizational skills training course
overcoming sales objections training course
performance management training course
personal branding training course
personal productivity training course
presentation skills training course
project management training course
proposal writing training course
prospecting and lead generation training course
public speaking training course
risk assessment and management training course
safety in the workplace training course
sales fundamentals training course
servant leadership training course
social intelligence training course
social learning training course
social media in the workplace training course
social media marketing training course
stress management training course
supervising others training course
supply chain management training course
taking initiative training course
talent management training course
team building for managers training course
team building through chemistry training course
teamwork and team building training course
telephone etiquette training course
telework and telecommuting training course
time management training course
top 10 sales secrets training course
trade show staff training course
train the trainer training course
virtual team building and management training course
women in leadership training course
work life balance training course
workplace diversity training course
workplace harassment training course
workplace violence training course
half day memory improvement courses workshops
speed reading courses workshops in singapore
10 soft skills you need corporate training course in singapore
administrative office procedures corporate training course in singapore
administrative support corporate training course in singapore
anger management corporate training course in singapore
appreciative inquiry corporate training course in singapore
archiving and records management corporate training course in singapore
self confidence assertiveness corporate training course in singapore
improving your attention management corporate training course in singapore
basic bookkeeping corporate training course in singapore
being a likeable boss corporate training course in singapore
body language basics corporate training course in singapore
budgets and financial reports corporate training course in singapore
business acumen corporate training course in singapore
business ethics corporate training course in singapore
business etiquette corporate training course in singapore
business succession planning corporate training course in singapore
business writing corporate training course in singapore
call center corporate training course in singapore
change management corporate training course in singapore
civility in the workplace corporate training course in singapore
coaching and mentoring corporate training course in singapore
coaching salespeople corporate training course in singapore
collaborative business writing corporate training course in singapore
communication strategies corporate training course in singapore
conducting annual employee reviews corporate training course in singapore
conflict resolution corporate training course in singapore
contact center corporate training course in singapore
contract management corporate training course in singapore
creating a great webinar corporate training course in singapore
creative problem solving corporate training course in singapore
crisis-management corporate training course in singapore
critical thinking corporate training course in singapore
customer service corporate training course in singapore
customer support corporate training course in singapore
cyber security corporate training course in singapore
delivering constructive criticism corporate training course in singapore
developing a lunch and learn corporate training course in singapore
developing corporate behavior corporate training course in singapore
developing creativity corporate training course in singapore
developing new managers corporate training course in singapore
digital citizenship corporate training course in singapore
emotional intelligence corporate training course in singapore
employee motivation corporate training course in singapore
employee onboarding corporate training course in singapore
employee recognition corporate training course in singapore
employee recruitment corporate training course in singapore
employee termination processes corporate training course in singapore
entrepreneurship training course in singapore
event planning corporate training course in singapore
executive and personal assistants corporate training course in singapore
facilitation skills corporate training course in singapore
generation gaps corporate training course in singapore
goal setting and getting things done corporate training course in singapore
handling a difficult customer corporate training course in singapore
health and wellness at work corporate training course in singapore
high performance teams inside the company corporate training course in singapore
high performance teams remote workforce corporate training course in singapore
hiring strategies corporate training course in singapore
human resource management corporate training course in singapore
improving mindfulness corporate training course in singapore
improving self awareness corporate training course in singapore
increasing your happiness corporate training course in singapore
internet marketing fundamentals corporate training course in singapore
interpersonal skills corporate training course in singapore
job search skills corporate training course in singapore
knowledge management corporate training course in singapore
leadership and influence corporate training course in singapore
lean process and six sigma corporate training course in singapore
life coaching essentials corporate training course in singapore
manager management corporate training course in singapore
managing personal finances corporate training course in singapore
marketing basics corporate training course in singapore
measuring results from corporate training course in singapore
media and public relations corporate training course in singapore
meeting management corporate training course in singapore
middle manager corporate training course in singapore
millennial onboarding corporate training course in singapore
mlearning essentials corporate training course in singapore
motivating your sales team corporate training course in singapore
negotiation skills corporate training course in singapore
networking outside the company corporate training course in singapore
networking within the company corporate training course in singapore
office politics for managers corporate training course in singapore
organizational skills corporate training course in singapore
overcoming sales objections corporate training course in singapore
performance management corporate training course in singapore
personal branding corporate training course in singapore
personal productivity corporate training course in singapore
presentation skills corporate training course in singapore
project management corporate training course in singapore
proposal writing corporate training course in singapore
prospecting and lead generation corporate training course in singapore
public speaking corporate training course in singapore
[url