turniej.unreal.pl :: Zobacz temat - [php5] Tworzenie kanału RSS 2.0 w PHP5
graphic logo logo graphic graphic  


[php5] Tworzenie kanału RSS 2.0 w PHP5
Napisz nowy temat   Odpowiedz do tematu
   Forum turniej.unreal.pl Strona Główna -> PHP, MySQL & Apache -> Tutoriale  
Autor Wiadomość
 Post Wysłany: Wto Gru 25, 2007 11:51 am 

Raven
Admin
Admin


Dołączył: 13 Maj 2004
Posty: 200


 
 
 

[php5] Tworzenie kanału RSS 2.0 w PHP5
Zobacz pojedynczy postZobacz pojedynczy post

     Bardzo modne stało się ostatnio dodawanie kanałów RSS (Really Simple Syndication) do stron WWW. Pozwala to na przeglądanie nagłówków i szybkie przechodzenie do najnowszych wiadomości, bez potrzeby uruchamiania samej strony.
     Oto jak może wyglądać przykładowy plik xml zawierający informacje:

PHP:


<?xml version="1.0" encoding="ISO-8859-2"?>

<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/">
   <channel>
      <title>Tytuł strony</title>
      <link>adres strony</link>
      <description>opis strony</description>
      <language>pl</language>
      <lastBuildDate>25.12.2007</lastBuildDate>
      <generator>generator</generator>
      <ttl>czas przechowywania</ttl>
      <image>
         <url>adres obrazka</url>
         <title>tytuł obrazka</title>         
         <link>link</link>
      </image>
      <item>
         <title>tytuł wiadomości</title>
         <link>link do pełnej wersji</link>
         <description><![CDATA[Tu możesz wstawić wszystko, łącznie z formatowaniem w XHTML]]></description>
      </item>
   </channel>
</rss>



na tej podstawie możemy utworzyć dwa szablony

plik: rss_main.xml
PHP:


<?xml version="1.0" encoding="ISO-8859-2"?>

<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/">
   <channel>
      <title>{rss_title}</title>
      <link>{rss_link}</link>
      <description>{rss_desc}</description>
      <language>{rss_lng}</language>
      <lastBuildDate>{rss_build}</lastBuildDate>
      <generator>{rss_gen}</generator>
      <ttl>{rss_ttl}</ttl>
      <image>
         <url>{img_src}</url>
         <title>{img_title}</title>         
         <link>{img_link}</link>
      </image>
{items}
   </channel>
</rss>



oraz

plik: rss_item.xml:
PHP:


      <item>
         <title>{item_title}</title>
         <link>{item_link}</link>
         <description><![CDATA[{item_data}]]></description>
      </item>



Pozostaje sprawa samego kodu, który przekształci powyższe szablony w kanał RSS 2.0. Pierwszym zadaniem będzie stworzenie danych zawierających konfigurację kanału:

PHP:


     $rss['rss_title']="turniej.unreal.pl";
     $rss['rss_link']="http://turniej.unreal.pl";
     $rss['rss_desc']="Kanał RSS serwisu turniej.unreal.pl";
     $rss['rss_lng']="pl";
     $rss['rss_gen']="turniej.unreal.pl";
     $rss['rss_ttl']=60;
     $rss['img_src']="http://turniej.unreal.pl/system/gfx/rss.jpg";
     $rss['img_title']="turniej.unreal.pl";
     $rss['img_link']="http://turniej.unreal.pl";  



     Kolejnym krokiem będzie określenie niezbędnych funkcji. Potrzebna nam będzie funkcja, która pobierze dane, przekształci zmienne z konfiguracji i połączy je z plikiem XML, zamieni wartości pomiędzy '{' i '}' na odpowiednie dane, i w końcu zwróci wynik działania. Można to wszystko zrobić jako jedną funkcję, ale od czego mamy nowe możliwości PHP5?

     Zróbmy zatem interfejs i klasę:

PHP:

<?php

/**
 * @author Raven
 * @copyright 2007
 *
 * rss interface 
 */

interface rss
{
&
nbsp/* renders feed */
&nbsp; static function RenderFeed($config);&nbsp; &nbsp;
&
nbsp/* parases XML file */
&nbsp; static function ParaseXML($xml$values);
&
nbsp/* gets main feed */
&nbsp; static function GetFeed($config);
&
nbsp/* returns items */
&nbsp; static function getItems($optional=false);
}

class 
rssfeed implements rss
{
/* 
Tu będą funkcje
*/
}
?>



i przejdźmy do funkcji ParaseXML. Do przetworzenia pliku XML będą na potrzebne tylko i wyłącznie wyrażenia regularne:

PHP:

    static function ParaseXML($xml, $content)
    {
        if(!file_exists($xml))
        {
            return false;
        }
        else
        {
            $fd = fopen($xml, "r");
            $template = fread ($fd, filesize($xml));
            fclose ($fd);
            foreach ($content as $key => $value)
            {
      $template = preg_replace('/\{'.$key.'\}/', $value, $template);
            }                  
            return $template;
        }
    }



     Prześledźmy działanie funkcji. Jeśli powiedzie się próba otwarcia pliku zawierającego szablon - jest on wczytywany do pamięci. Potem zaś parametry są rozbijane na klucz oraz wartość i wstawiane do wyrażenia regularnego, które zastępuje dane pozycje - właściwymi danymi. W tej chwili mamy najtrudniejszą robotę z głowy. Co nam pozostało, to odpowiednie wstawianie zmiennych.
     Główna funkcja kompilująca - GetFeed - zajmuje się przekształcaniem danych z konfiguracji, tworzeniem nagłówka i wywołaniem funkcji pobierającej właściwe dane:

PHP:

   static function GetFeed($config)
   {   
      foreach ($config as $key => $value)
      {
         $template_vars[$key]=$value;
      }
      $template_vars['items']=self::getItems();
      $template_vars['rss_build']=date('d F Y, H:i',time());   
      return self::ParaseXML("rss_main.xml", $template_vars);
   }



funkcja getItems może wyglądać tak:

PHP:


   static function getItems($optional=false)
   {      
      $items="";
/*
Poniższy fragmen to przykład
*/
      $template_vars['item_title']="Nowy news";
      $template_vars['item_link']="http://turniej.unreal.pl";
      $template_vars['item_data']="<b>To jest test</b>";
      $items .= self::ParaseXML("rss_item.xml", $template_vars);

      return $items;
   }


Jest to tylko prosty przykład jak wstawiać dane do zmiennej i jak wywołać funkcję przetważającą plik XML. W tym miejscu należy wstawić funkcje pobierającą newsy z bazy danych, itp.

     Na koniec zaś funkcja publiczna:
PHP:


    public static function RenderFeed($config)
    {
   return self::GetFeed($config);
    }



Niestety nie jest to koniec. Aby efekt działania funkcji był widoczny dla przeglądarki jako kanał RSS należy ustawić odpowiedni nagłówek:
PHP:

header("Content-Type: application/xml; charset=ISO-8859-2");


i nie będzie kłopotu. Gotowy plik może wyglądać tak:

plik: rss.php
PHP:

<?php

/**
 * @author Raven
 * @copyright 2007
 * @created 18:27 24.12.2007
 * Released under GPL License.
 */
header("Content-Type: application/xml; charset=ISO-8859-2");&nbsp; &nbsp;
$rss['rss_title']="turniej.unreal.pl";
$rss['rss_link']="http://turniej.unreal.pl";
$rss['rss_desc']="Kanał RSS serwisu turniej.unreal.pl";
$rss['rss_lng']="pl";
$rss['rss_gen']="turniej.unreal.pl";
$rss['rss_ttl']=60;
$rss['img_src']="http://turniej.unreal.pl/system/gfx/rss.jpg";
$rss['img_title']="turniej.unreal.pl";
$rss['img_link']="http://turniej.unreal.pl";&nbsp; &nbsp


interface 
rss
{
&
nbsp/* renders feed */
&nbsp; public static function RenderFeed($config);&nbsp; &nbsp;
&
nbsp/* parases XML file */
&nbsp; static function ParaseXML($xml$values);
&
nbsp/* gets main feed */
&nbsp; static function GetFeed($config);
&
nbsp/* returns items */
&nbsp; static function getItems($optional=false);

&
nbsp
class 
rssfeed implements rss
{&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;
&
nbsp; &nbsp/* renders feed */
&nbsp; &nbsp;public static function RenderFeed($config)
&
nbsp; &nbsp; {
&
nbsp; &nbsp;&nbsp; &nbsp;return self::GetFeed($config);
&
nbsp; &nbsp;}
&
nbsp; &nbsp;/* parases XML file */
&nbsp; &nbsp;static function ParaseXML($xml$content)
&
nbsp; &nbsp; {
&
nbsp; &nbsp; &nbsp; &nbsp; if(!file_exists($xml))
&
nbsp; &nbsp; &nbsp; &nbsp; {
&
nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false;
&
nbsp; &nbsp; &nbsp; &nbsp; }
&
nbsp; &nbsp; &nbsp; &nbsp; else
&
nbsp; &nbsp; &nbsp; &nbsp; {
&
nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp$fd fopen($xml"r");
&
nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp$template fread ($fdfilesize($xml));
&
nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbspfclose ($fd);
&
nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;foreach ($content as $key => $value)
&
nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;{
&
nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;$template preg_replace('/\{'.$key.'\}/'$value$template);
&
nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp;
&
nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;return $template;
&
nbsp; &nbsp; &nbsp; &nbsp; }
&
nbsp; &nbsp; }
&
nbsp; &nbsp/* gets main feed */
&nbsp; &nbsp; static function GetFeed($config)
&
nbsp; &nbsp;{&nbsp; &nbsp;
&
nbsp; &nbsp;&nbsp; &nbsp;foreach ($config as $key => $value)
&
nbsp; &nbsp;&nbsp; &nbsp;{
&
nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;$template_vars[$key]=$value;
&
nbsp; &nbsp;&nbsp; &nbsp;}
&
nbsp; &nbsp;&nbsp; &nbsp;$template_vars['items']=self::getItems();
&
nbsp; &nbsp;&nbsp; &nbsp;$template_vars['rss_build']=date('d F Y, H:i',time());&nbsp; &nbsp;&nbsp; &nbsp;
&
nbsp; &nbsp;&nbsp; &nbsp;
&
nbsp; &nbsp;&nbsp; &nbsp;return self::ParaseXML("rss_main.xml"$template_vars);
&
nbsp; &nbsp;}
&
nbsp; &nbsp;/* returns items */&nbsp; &nbsp;
&
nbsp; &nbsp;static function getItems($optional=false)
&
nbsp; &nbsp;{
&
nbsp; &nbsp;&nbsp; &nbsp;global $_DB;
&
nbsp; &nbsp;&nbsp; &nbsp;
&
nbsp; &nbsp;&nbsp; &nbsp;$items="";&nbsp; &nbsp;
/*
Poniższy fragmen to przykład
*/
&nbsp; &nbsp;&nbsp; &nbsp;$template_vars['item_title']="Nowy news";
&
nbsp; &nbsp;&nbsp; &nbsp;$template_vars['item_link']="http://turniej.unreal.pl";
&
nbsp; &nbsp;&nbsp; &nbsp;$template_vars['item_data']="<b>To jest test</b>";
&
nbsp; &nbsp;&nbsp; &nbsp;$items .= self::ParaseXML("rss_item.xml"$template_vars);
&
nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;
&
nbsp; &nbsp;&nbsp; &nbsp;return $items;
&
nbsp; &nbsp;}
&
nbsp; &nbsp;
}
echo 
rssfeed::RenderFeed($rss);
?>



Aby informacja o istnieniu kanału pojawiała się na stronie, należy w nagłówkach XHTML dodać:
PHP:

<link rel="alternate" type="application/rss+xml" title="turniej.unreal.pl RSS Feed" href="rss.php" />



Oczywiście jest to tylko prosty przykład, który może być dalej rozbudowywany.

 
Odpowiedz z cytatem

_________________

personal wiki
Zobacz profil autora Wyślij prywatną wiadomość Wyślij email Odwiedź stronę autora Numer GG Tlen
   Forum turniej.unreal.pl Strona Główna -> PHP, MySQL & Apache -> Tutoriale
Napisz nowy temat   Odpowiedz do tematu
Skocz do:  

 Further options
 Wszystkie czasy w strefie GMT
Strona 1 z 1
 
Zobacz poprzedni temat :: Zobacz następny temat  
Nie możesz pisać nowych tematów
Nie możesz odpowiadać w tematach
Nie możesz zmieniać swoich postów
Nie możesz usuwać swoich postów
Nie możesz głosować w ankietach
Nie możesz dołączać plików na tym forum
Nie możesz ściągać plików na tym forum
Wyświetl posty z ostatnich:   
 

turniej.unreal.pl Kanał RSS tematu 
PicLens 

Powered by phpBB © 2001, 2002 phpBB Group
Illusion template v.1.0.2 © Jasidog.com
Powered by phpbb, copyright the phpbb group Template by jasidog.com