← Tutoriais

[PHP & CSS] Feed Reader

Lida 8171 vezes

Offline

=IceBurn= 
Membro
Mensagens 897 Gostos 3
Feedback +3

Troféus totais: 32
Trófeus: (Ver todos)
Windows User Level 6 Linux User Mobile User Super Combination Combination Topic Starter Poll Voter Poll Starter Level 5

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:
 :arrow: index.php
 :arrow: feedreader.class.php
 :arrow: estilo.css

Comecemos 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'.

 :arrow: feedreader.class.php
Código: [Seleccione]
<?php
/**
* @author João Romão [www.jrfreelancer.com&#93;
* @copyright 2007
*/
class FeedReader &#123; 
  
   
var $feed_url    'http&#58;//www.correiomanha.pt/rss/rss.asp';
   var 
$timeout     15;
   var 
$decode_utf8 true;
   var 
$header      = array&#40;&#41;;
   
var $insideitem  false
   var 
$tag         ''
   var 
$title       ''
   var 
$description ''
   var 
$link        ''

   function 
startElement&#40;$parser, $tagname&#41; &#123; 
    
if&#40;$this->insideitem&#41; &#123; 
 
 $this->tag $tagname

&#125; else if &#40;$tagname == "ITEM"&#41; &#123; 
 
 $this->insideitem true

&#125; 
   
   
&#125; 

   
   
function endElement&#40;$parser, $tagname&#41; &#123; 
       
   if &#40;$tagname == "ITEM"&#41; &#123; 
           
   printf&#40;"\t<a href='%s' class='descricao' onclick='window.open&#40;this.href&#41;; return false;'>%s<span>%s</span></a>\n\n", 
          htmlentities&#40;trim&#40;$this->link&#41;&#41;,
  trim&#40;strip_tags&#40;$this->title&#41;&#41;,
  trim&#40;str_replace&#40;'&nbsp;', ' ', strip_tags&#40;$this->description&#41;&#41;&#41;
  &#41;; 
           
   $this->title       ""
   $this->description ""
           
$this->link        ""
           
$this->insideitem  false
       &
#125; 
   
&#125; 

   
function characterData&#40;$parser, $text&#41; &#123; 
       
 if&#40;$this->insideitem&#41; &#123; 
    
switch &#40;$this->tag&#41; &#123; 

 case "TITLE"       &#58; $this->title       .= &#40;$this->decode_utf8 == true&#41; ? utf8_decode&#40;$text&#41; &#58; $text;  break; 
 case "DESCRIPTION" &#58; $this->description .= &#40;$this->decode_utf8 == true&#41; ? utf8_decode&#40;$text&#41; &#58; $text;  break; 
         
case "LINK"        &#58; $this->link        .= &#40;$this->decode_utf8 == true&#41; ? utf8_decode&#40;$text&#41; &#58; $text;  break;
        
&#125;
  
  &#125; 
     
   
&#125; 


  
function feed_get_contents&#40;$url&#41;&#123;
 array_push&#40;$this->header, $_SERVER["HTTP_ACCEPT"&#93;&#41;;
     
$ch curl_init&#40;&#41;;
     
curl_setopt &#40;$ch, CURLOPT_URL, $url&#41;;
     
curl_setopt &#40;$ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT'&#93;&#41;;
     
curl_setopt &#40;$ch, CURLOPT_HTTPHEADER, $this->header&#41;;
     
curl_setopt &#40;$ch, CURLOPT_FOLLOWLOCATION, true&#41;;
     
curl_setopt &#40;$ch, CURLOPT_RETURNTRANSFER, 1&#41;;
     
curl_setopt &#40;$ch, CURLOPT_CONNECTTIMEOUT, $this->timeout&#41;;
     
$feed_contents =  curl_exec&#40;$ch&#41;;
     
curl_close&#40;$ch&#41;;
    
return $feed_contents;
  &
#125;

 
  
function parse_feed&#40;&#41; &#123;
    
$this->parser xml_parser_create&#40;&#41;;
                    
xml_set_object&#40;$this->parser, &$this&#41;;
                    
xml_set_element_handler&#40;$this->parser, 'startElement', 'endElement'&#41;; 
                    
xml_set_character_data_handler&#40;$this->parser, 'characterData'&#41;; 
                    
return xml_parse&#40;$this->parser, $this->feed_get_contents&#40;$this->feed_url&#41;&#41;;
                    
xml_parser_free&#40;$this->parser&#41;;
  
  
&#125;


&#125; 
?>



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)
 
:arrow: estilo.css
Código: [Seleccione]
/**
* @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

 :arrow: index.php
Código: [Seleccione]
<!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&#40;'./classes/feedreader.class.php'&#41;;
    
$feed_reader = new FeedReader&#40;&#41;;
$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" &#58;&#41;
    
$feed_reader->feed_url 'http&#58;//www.correiomanha.pt/rss/rss.asp'// --> URL da feed que queremos apresentar
    
$feed_reader->parse_feed&#40;&#41;;
   
?>

 
  </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> &copy; 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  :arrow: http://jrfreelancer.com/tutoriais/demos/feed_reader/

E pronto, espero que gostem :wink:

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.
Offline

cenourinha 
Elite
Mensagens 4094 Gostos 21
Troféus totais: 34
Trófeus: (Ver todos)
Mobile User Apple User Level 6 Super Combination Combination Topic Starter 10 Poll Votes Poll Voter Level 5 Level 4

Foste tu que fizestes o parser?
mt bom
 :D
Offline

=IceBurn= 
Membro
Mensagens 897 Gostos 3
Feedback +3

Troféus totais: 32
Trófeus: (Ver todos)
Windows User Level 6 Linux User Mobile User Super Combination Combination Topic Starter Poll Voter Poll Starter Level 5

Sim, o parser é a parte mais fácil, pois a regra é sempre a mesma. O PHP já tem funções muito específicas para XML, depois é só "construir".
Obrigado.
Offline

cenourinha 
Elite
Mensagens 4094 Gostos 21
Troféus totais: 34
Trófeus: (Ver todos)
Mobile User Apple User Level 6 Super Combination Combination Topic Starter 10 Poll Votes Poll Voter Level 5 Level 4

Eu custumo usar o magieRSS ou o LastRSS parser para as minhas apps...
por exemplo:
psp.webtuga.com
iphone.webtuga.com
www.webtuga.com/wap/
Offline

leite 
Membro
Mensagens 864 Gostos 11
Troféus totais: 29
Trófeus: (Ver todos)
Mobile User Apple User Super Combination Combination Topic Starter 10 Poll Votes Poll Voter Poll Starter Level 5 Level 4

Offline

=IceBurn= 
Membro
Mensagens 897 Gostos 3
Feedback +3

Troféus totais: 32
Trófeus: (Ver todos)
Windows User Level 6 Linux User Mobile User Super Combination Combination Topic Starter Poll Voter Poll Starter Level 5

Citação de: "cenourinha"
Eu custumo usar o magieRSS ou o LastRSS parser para as minhas apps...
por exemplo:
psp.webtuga.com
iphone.webtuga.com
www.webtuga.com/wap/

Pois,  não conheço nem um nem outro.
Mas gostei daquela entrada numa feed:  Deus era programador... :lol:
Offline

cenourinha 
Elite
Mensagens 4094 Gostos 21
Troféus totais: 34
Trófeus: (Ver todos)
Mobile User Apple User Level 6 Super Combination Combination Topic Starter 10 Poll Votes Poll Voter Level 5 Level 4

Já tá direito.
Offline

cenourinha 
Elite
Mensagens 4094 Gostos 21
Troféus totais: 34
Trófeus: (Ver todos)
Mobile User Apple User Level 6 Super Combination Combination Topic Starter 10 Poll Votes Poll Voter Level 5 Level 4

Citação de: "=IceBurn="
Citação de: "cenourinha"
Eu custumo usar o magieRSS ou o LastRSS parser para as minhas apps...
por exemplo:
psp.webtuga.com
iphone.webtuga.com
www.webtuga.com/wap/

Pois,  não conheço nem um nem outro.
Mas gostei daquela entrada numa feed:  Deus era programador... :lol:


 :D

Desistiu ao oitavo dia... lol
Offline

=IceBurn= 
Membro
Mensagens 897 Gostos 3
Feedback +3

Troféus totais: 32
Trófeus: (Ver todos)
Windows User Level 6 Linux User Mobile User Super Combination Combination Topic Starter Poll Voter Poll Starter Level 5

Já agora um conselho para a página wap, atribui um doctype:
Código: [Seleccione]
<?xml version="1.0"  encoding="ISO-8859-1"?>
<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN"
"http://www.wapforum.org/DTD/xhtml-mobile10.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">


Alguns telémoveis não vão recenhecer a página e vão dar erro.

Recordo que o WAP foi por onde comecei :)
Offline

cenourinha 
Elite
Mensagens 4094 Gostos 21
Troféus totais: 34
Trófeus: (Ver todos)
Mobile User Apple User Level 6 Super Combination Combination Topic Starter 10 Poll Votes Poll Voter Level 5 Level 4

Citação de: "=IceBurn="
Já agora um conselho para a página wap, atribui um doctype:
Código: [Seleccione]
<?xml version="1.0"  encoding="ISO-8859-1"?>
<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN"
"http://www.wapforum.org/DTD/xhtml-mobile10.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">


Alguns telémoveis não vão recenhecer a página e vão dar erro.

Recordo que o WAP foi por onde comecei :)


andava agora à procura disso... tanks
:P
Offline

cenourinha 
Elite
Mensagens 4094 Gostos 21
Troféus totais: 34
Trófeus: (Ver todos)
Mobile User Apple User Level 6 Super Combination Combination Topic Starter 10 Poll Votes Poll Voter Level 5 Level 4

Coloquei isso mas agora a página dá em branco...
:|
Offline

=IceBurn= 
Membro
Mensagens 897 Gostos 3
Feedback +3

Troféus totais: 32
Trófeus: (Ver todos)
Windows User Level 6 Linux User Mobile User Super Combination Combination Topic Starter Poll Voter Poll Starter Level 5

Sim, dever ter error_reporting em 0, por isso não dá erro, mas sei qual é o problema.
Mete assim:
Código: [Seleccione]
<?php print '<?xml version="1.0"  encoding="ISO-8859-1"?>'; ?>
<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN"
"http://www.wapforum.org/DTD/xhtml-mobile10.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
Offline

cenourinha 
Elite
Mensagens 4094 Gostos 21
Troféus totais: 34
Trófeus: (Ver todos)
Mobile User Apple User Level 6 Super Combination Combination Topic Starter 10 Poll Votes Poll Voter Level 5 Level 4

Já deu, obrigado.
Offline

Souza 
Elite
Mensagens 1816 Gostos 1
Troféus totais: 28
Trófeus: (Ver todos)
Super Combination Combination Topic Starter 10 Poll Votes Poll Voter Level 5 Level 4 Level 3 Level 2 Level 1

Tá lindo iceburn  =D&gt;
Offline

Casteloes 
Membro
Mensagens 935 Gostos 0
Feedback +14

Troféus totais: 31
Trófeus: (Ver todos)
Search Linux User Mobile User Windows User Super Combination Combination Topic Starter Poll Voter Level 5 Level 4

=IceBurn=
Parabens.