Boas!
Visto que se tem falado um pouco de Feeds RSS e como é notório por parte de alguns membros o interesse em mostrar noticias nos seus sites, resolvi criar mais um tutorial.
Assim fiz uma classe em PHP e dei um toque de web 2.0 no CSS. Nada de JavaScript, apenas CSS.
São necessários 3 ficheiros:
index.php feedreader.class.php estilo.cssComecemos então pela classe php... para ligar a feeds externas utilizei a biblioteca cURL do php, o que em principio será o melhor para muitos, visto que existe uma tendencia enorme em muitos hosts para desabilitarem 'allow url fopen'.
feedreader.class.php<?php
/**
* @author João Romão [www.jrfreelancer.com]
* @copyright 2007
*/
class FeedReader {
var $feed_url = 'http://www.correiomanha.pt/rss/rss.asp';
var $timeout = 15;
var $decode_utf8 = true;
var $header = array();
var $insideitem = false;
var $tag = '';
var $title = '';
var $description = '';
var $link = '';
function startElement($parser, $tagname) {
if($this->insideitem) {
$this->tag = $tagname;
} else if ($tagname == "ITEM") {
$this->insideitem = true;
}
}
function endElement($parser, $tagname) {
if ($tagname == "ITEM") {
printf("\t<a href='%s' class='descricao' onclick='window.open(this.href); return false;'>%s<span>%s</span></a>\n\n",
htmlentities(trim($this->link)),
trim(strip_tags($this->title)),
trim(str_replace(' ', ' ', strip_tags($this->description)))
);
$this->title = "";
$this->description = "";
$this->link = "";
$this->insideitem = false;
}
}
function characterData($parser, $text) {
if($this->insideitem) {
switch ($this->tag) {
case "TITLE" : $this->title .= ($this->decode_utf8 == true) ? utf8_decode($text) : $text; break;
case "DESCRIPTION" : $this->description .= ($this->decode_utf8 == true) ? utf8_decode($text) : $text; break;
case "LINK" : $this->link .= ($this->decode_utf8 == true) ? utf8_decode($text) : $text; break;
}
}
}
function feed_get_contents($url){
array_push($this->header, $_SERVER["HTTP_ACCEPT"]);
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt ($ch, CURLOPT_HTTPHEADER, $this->header);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $this->timeout);
$feed_contents = curl_exec($ch);
curl_close($ch);
return $feed_contents;
}
function parse_feed() {
$this->parser = xml_parser_create();
xml_set_object($this->parser, &$this);
xml_set_element_handler($this->parser, 'startElement', 'endElement');
xml_set_character_data_handler($this->parser, 'characterData');
return xml_parse($this->parser, $this->feed_get_contents($this->feed_url));
xml_parser_free($this->parser);
}
}
?>
Segue-se o ficheiro estilo.css... tenham especial atenção que é aqui que está a magia da grande potencialidade que o CSS nos oferece... (quando virem a demo vão perceber do que estou a falar)
estilo.css/**
* @author João Romão [www.jrfreelancer.com]
* @copyright 2007
*/
body {
font-family: "Myriad Web", "Myriad Pro", "Gill Sans", Helvetica, Arial, Sans-Serif;
color: #D2D2D2;
background-color: #4B4B4B;
font-size: 14px;
}
img { border: none; }
h1 { color: #FFA500; margin: 2px auto 2px 0; font-size: 50px; letter-spacing: -5px }
div#container {
background: #4B4B4B url('../design/rss.gif') no-repeat top right;
margin: 100px auto auto auto;
padding: 10px;
width: 300px !important;
}
/***********************************/
/*** NÃO RETIRAR, INDESPENSÁVEL ****/
/***********************************/
a.descricao {
display: block;
margin: 0;
position: relative;
z-index:24;
color:#00CCFF;
text-decoration:none;
font-size: 14px;
font-weight: normal;
}
a.descricao:hover { position: relative; z-index:25; background-color:#5A5A5A; text-indent: 5px; }
a.descricao span { display: none; }
a.descricao:hover span {
display: block;
position: absolute;
top: 20px;
right: 0px;
width: 250px;
border: 1px solid #D2D2D2;
background-color: #FAF8F9;
color: #5A5A5A;
text-align: left;
padding: 5px;
}
/***********************************/
/***********************************/
/***********************************/
div#footer {
width: 90%;
margin: auto;
text-align: center;
font-family: monospace, sans-serif, verdana;
}
div#footer p { margin: 2px; }
div#footer p#creativecommuns { margin-top: 20px; }
div#footer a { color: #FFD400; text-decoration: none; }
div#footer a:hover { text-decoration: underline; }
E por último, o ficheiro onde vamos chamar a classe e visualizar as feeds
index.php<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="pt" lang="pt">
<head>
<title>Feed Reader | Por João Romão (=IceBurn=) | jrfreelancer.com - Programação Desenvolvimento Sites WEB| PHP CSS XHTML</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<meta name="author" content="IceBurn" />
<style type="text/css" media="all">@import "./css/estilo.css";</style>
</head>
<body>
<div id="container">
<h1>Feed Reader</h1>
<p>
<?php
require('./classes/feedreader.class.php');
$feed_reader = new FeedReader();
$feed_reader->timeout = 10; // --> Se não conectar à feed em x segundos, o código desiste e prossegue. Mais de 15 é desaconselhável.
$feed_reader->decode_utf8 = false; // --> Altere para true se vir "caracteres esquesitos" :)
$feed_reader->feed_url = 'http://www.correiomanha.pt/rss/rss.asp'; // --> URL da feed que queremos apresentar
$feed_reader->parse_feed();
?>
</p>
</div>
<div id="footer">
<p>Download: <a href="http://jrfreelancer.com/tutoriais/feed_reader.rar">feed_reader.rar (7.81 KB)</a></p>
<p>By =IceBurn= <a href="http://jrfreelancer.com">www.jrfreelancer.com</a> © 2007</p>
<p id="creativecommuns">
<a href="http://creativecommons.org/licenses/by-nc/2.5/pt/" onclick="window.open(this.href); return false;"><img alt="Creative Commons License" src="http://creativecommons.org/images/public/somerights20.png"/></a>
</p>
</div>
</body>
</html>
Demo e download disponíveis aqui
http://jrfreelancer.com/tutoriais/demos/feed_reader/E pronto, espero que gostem
PS: Se resolverem utilizar em algum site, digam o link, é sempre bom ver o nosso trabalho em acção
Não precisam de incluir copyrights visíveis no site, por isso estejam à vontade.