Rss feed generator

Release your script here.
State:
- Author
- What it does
- Perhaps a little guide.
- Also, if the snippet is of any use to the community, it has a chance of getting posted on the main page, so don't hesitate to submit/ask!

Rss feed generator

Postby Dandy » Mon Jun 09, 2008 4:04 pm

Im releasing a php script that generates a full rss feed, the script is well documented and commented, using oop style so see if you can learn from it ;)

http://daasor.info/files/rss-1.0.1.tar.gz

examples included

requires php5 to work

http://daasor.info/docs/rss-1.0.1 for documentation (includes in the tarball aswell)

Edit: updated to version 1.0.1
Last edited by Dandy on Mon Jun 30, 2008 4:55 pm, edited 2 times in total.
Dandy
 

Re: Rss feed generator

Postby Cristian » Mon Jun 09, 2008 4:13 pm

Very nice, I love your release its so well commented in the files, good job.
Cristian
proof of advance
proof of advance
 
Posts: 282
Joined: Sun Nov 04, 2007 3:02 pm
Location: Denmark
Authnick: Sumsar

Re: Rss feed generator

Postby Dandy » Mon Jun 09, 2008 4:54 pm

To mention it, i've tested the class but the example file supplied is not tested, and the values put in there does not work for you nessecarily
Dandy
 

Re: Rss feed generator

Postby Cristian » Mon Jun 09, 2008 5:01 pm

Good information, I'll try it out sometime, when I've got the time.
Cristian
proof of advance
proof of advance
 
Posts: 282
Joined: Sun Nov 04, 2007 3:02 pm
Location: Denmark
Authnick: Sumsar

Re: Rss feed generator

Postby Lukemob » Sun Jun 15, 2008 12:49 pm

Yeah, same here. Maybe one nice day I will try it (When I have time) :-)
Lukemob
 

Re: Rss feed generator

Postby Cristian » Mon Jun 30, 2008 6:44 am

Hey Dandy, now I'm trying your php rss feed generator, and I stumbled into some errors, my php skills aren't so good, but here is the error message.

Parse error: syntax error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or '}' in /*/*/*/*/rss.php on line 43

if you need more information please tell me, I'm eager to try out this script.
Cristian
proof of advance
proof of advance
 
Posts: 282
Joined: Sun Nov 04, 2007 3:02 pm
Location: Denmark
Authnick: Sumsar

Re: Rss feed generator

Postby Dandy » Mon Jun 30, 2008 7:34 am

Updated: There was no issue with this Code, but it Requires php 5 (Sumsar). I'll proberly release a version for php4 later.

Code: Select all
<?php
/**
 * File:        Rss.php
 *
 * This code is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This code is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * @link http://www.daasor.info/
 * @copyright 2008 daasor.info
 * @author Daniel Sørensen <daniel at daasor.info>
 * @package Rss
 * @version 1.0.1
 */
 /**
 * Changelog
 *
 * 1.0.1:
 * Created missing function
 * Updated comments in the class.
 *
 * 1.0:
 * Initial Release
 */
 
/**
 * Handles Rss in a more fasionable way.
 * @package Rss
 * @class RssGenerator
 */
class RssGenerator
{
    /**
    * @var array $mappings Maps database columns to Rss nodes.
    * @access private
    */
    private $mappings;/* = array('guid'=>'','link'=>'','description'=>'','title'=>'','pubDate'=>'','category'=>'','author'=>''); */
   
    /**
    * @var array $channel Channel information
    * @access private
    */
    private $channel;/* = array('title' => 'RSS Feed Generator','link' => '','description' => 'Feed generated by RssGenerator (http://www.daasor.info)','language' => 'en','pubDate' => '','lastBuildDate' => '','docs' => 'http://blogs.law.harvard.edu/tech/rss');*/
   
    /**
    * @var array $functionMap Maps database columns to Rss nodes using custom functions.
    * @access private
    */
    private $functionMap;/* = array('guid'=>null,'link'=>null,'description'=>null,'title'=>null,'pubDate'=>null,'category'=>null,'author'=>null);*/
   
    /**
    * @var int $numRows Number of rows to get.
    * @access private
    */
    private $numRows = 15;
   
    /**
    * @var string $mysqlHost mySQL hostname (defaults to localhost)
    * @access private
    */
    private $mysqlHost = "localhost";
   
    /**
    * @var string $mysqlUser mySQL username
    * @access private
    */
    private $mysqlUser;
   
    /**
    * @var string $mysqlPass mySQL password
    * @access private
    */
    private $mysqlPass;
   
    /**
    * @var string $mysqlDatabase mySQL Database
    * @access private
    */
    private $mysqlDatabase;
   
    /**
    * @var string $mysqlTable mySQL table
    * @access private
    */
    private $mysqlTable = "";
   
    /**
    * @var string $mysqlTableIndexField mySQL table index field
    * @access private
    */
    private $mysqlTableIndexField = "id";
   
    /**
    * @var boolean $mysqlTablePubdateInt Is pubDate field int?
    * @access private
    */
    private $mysqlTablePubdateInt = false;
   
    /**
    * @desc mysql link
    * @access private
    */
    private $mysqlLink = null;
   
    /**
    * @var int $throwErrors (0/1/2) Decides whether errors should be thrown or not.
    * @desc 0 = Don't 1 = raise a user error 2 = throw exceptions
    * @access private
    */
    private $throwErrors = 0;
   
   
    /**
    * @desc class contructor
    */
    public function __construct()
    {
   $this->mappings = array('guid'=>'','link'=>'','description'=>'','title'=>'','pubDate'=>'','category'=>'','author'=>'');
   $this->functionMap = array('guid'=>null,'link'=>null,'description'=>null,'title'=>null,'pubDate'=>null,'category'=>null,'author'=>null);
   $this->channel = array('title' => 'RSS Feed Generator','link' => '','description' => 'Feed generated by RssGenerator (http://www.daasor.info)','language' => 'en','pubDate' => '','lastBuildDate' => '','docs' => 'http://blogs.law.harvard.edu/tech/rss');
        $this->channel['link'] = 'http://'.$_SERVER['HTTP_HOST'];
        $this->channel['pubDate'] = $this->formatDate(time());
        $this->channel['lastBuildDate'] = $this->formatDate(time());
        $this->mapFunction('pubDate',array(&$this,'formatDate'));
    }
   
    /**
    * @desc Formats date for rss feed
    * @access private
    * @param {int} $input Seconds since epoch
    * @return {string} formatted date
    */
    private function formatDate($input)
    {
        return date('D, d M Y H:i:s O',$input);
    }
   
    /**
    * @desc Throws an error
    * @access private
    * @param string $str Error message
    */
   
    private function throwError($str) {
        if ($this->throwErrors == 1)
        {
            trigger_error('RssGenerator: '.$str,E_USER_ERROR);
        } else if ($this->throwErrors == 2)
        {
            throw new Exception('RssGenerator: '.$str);
        }
    }
    /**
    * @desc Connects to the mysql database
    * @access private
    */
    private function connect()
    {
        $this->mysqlLink = mysql_connect($this->mysqlHost,$this->mysqlUser,$this->mysqlPass);
        if ($this->mysqlLink)
        {           
            if (!mysql_select_db($this->mysqlDatabase))
            {
                $this->throwError('Could not select Database');
            }
        } else {
            $this->throwError('Could not connect to mySQL host.');
        }
    }
    /**
    * @desc Maps a column to a Rss node.
    * @access public
    * @param string $column mysql column name
    * @param string $node rss node name
    */
    public function map($column,$node)
    {
        if (array_key_exists($node,$this->mappings))
        {
            $this->mappings[$node] = $column;
        } else {
            $this->throwError('Unknown node');
        }
    }
    /**
    * @desc Sets channel information
    * @access public
    * @param string $field Channel field to update
    * @param string $value new value
    */
    public function setChannel($field,$value)
    {
        if (array_key_exists($field,$this->channel))
        {
            $this->channel[$field] = $value;
        } else {
            $this->throwError('Unknown channel field');
        }
    }   
    /**
    * @desc Maps a column to a custom function
    * @access public
    * @param string $node rss node name
    * @param mixed $function array/string function name or an array with class name and method name
    */
    public function mapFunction($node,$function)
    {
        if (array_key_exists($node,$this->functionMap))
        {
            $this->functionMap[$node] = $function;
        } else {
            $this->throwError('Unknown node');
        }
    }
    /**
    * @desc Prepare value for the rss feed
    * @access private
    * @param string $node rss node name
    * @param string $value value from mysql table
    * @param int $row values for the row
    * @return string Prepared value for rss feed.
    */
    private function prepareNode($node,$value,$row)
    {
        if ($this->functionMap[$node] != null)
        {
            return call_user_func($this->functionMap[$node],$value,$row);
        } else {
            return $value;
        }
    }
    /**
    * @desc Queries the database
    * @access private
    * @param string $query Query to execute
    * @return array results
    */
    private function query($query)
    {
        if ($this->mysqlLink == null)
        {
            $this->connect();
        }
        $queryResults = mysql_query($query,$this->mysqlLink);
        if (!$queryResults)
        {
            $this->throwError(mysql_error());
        }
        $results = array();
        while ($array = mysql_fetch_array($queryResults))
        {
            array_push($results,$array);
        }
        return $results;

    }
    /**
    * @desc Set a setting in the class
    * @access public
    * @param string $setting Setting to update
    * @param mixed $value New value to set
    */
    public function set($setting,$value)
    {
        if (property_exists($this,$setting))
        {
            if (is_array($this->$setting) || strtolower($setting) == "mysqllink")
            {
                $this->throwError('You are not allowed to update that value.');
            } else {
                $this->$setting = $value;
            }
        }
        else {
            $this->throwError('Property does not exist.');
        }
    }
    /**
    * @desc Builds the feed
    * @access public
    */
    public function build()
    {
        // Create Document and Set encoding
        $document = new DOMDocument('1.0');
        $document->encoding = 'UTF-8';
       
        $root = $document->createElement('channel');
        // add the channel information
        foreach ($this->channel as $field => $value)
        {
            $tmp = $document->createElement($field);
            $tmp->appendChild($document->createTextNode($value));
            $root->appendChild($tmp);
            $tmp = null;
        }
       
        $fields = array('`'.$this->mysqlTableIndexField.'`');
        // builds field to select
        foreach ($this->mappings as $node => $field)
        {
            if ($field != '')
            {
                if ($node == 'pubDate')
                {
                    if ($this->mysqlTablePubdateInt == false)
                    {
                        $fields[] = "UNIX_TIMESTAMP(`".$field."`) `".$field."`";
                    } else {
                        $fields[] = "`".$field."`";
                    }
                } else {
                    $fields[] = "`".$field."`";
                }
            }
        }
        $fields = array_unique($fields);
        $fieldString = join(',',$fields);
        // Build query
        $query = sprintf("SELECT %s FROM %s ORDER BY %s DESC LIMIT %d",$fieldString,$this->mysqlTable,$this->mysqlTableIndexField,$this->numRows);
       
        $results = $this->query($query);
        if (is_array($results) && count($results) > 0)
        {
            $items = array();
            foreach ($results as $row)
            {
                $items[$object[$this->mysqlTableIndexField]] = array();
                $item = $document->createElement('item');
                foreach ($this->mappings as $node => $field)
                {
                    $items[$object[$this->mysqlTableIndexField]][$node] = $document->createElement($node);
                    $items[$object[$this->mysqlTableIndexField]][$node]->appendChild($document->createTextNode($this->prepareNode($node,$row[$field],$row)));
                    $item->appendChild($items[$object[$this->mysqlTableIndexField]][$node]);
                }
                $root->appendChild($item);
            }
        }
        $document->appendChild($root);
        header("Content-type: application/xml; charset=utf-8");
        echo $document->saveXML();
       
    }
       
}

?>


I have not got this error myself so this is guessing, but i think this should do it. I've updated the __construct method and removed the initial values of 3 variables. Please do return to me if there are any other error. I'll update the Tarball later (lazy).
Dandy
 

Re: Rss feed generator

Postby Dandy » Fri Jul 04, 2008 6:28 pm

Code: Select all
<?php
/**
 * File:        Rss.php
 *
 * This code is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This code is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * @link http://www.daasor.info/
 * @copyright 2008 daasor.info
 * @author Daniel Sørensen <daniel at daasor.info>
 * @package Rss
 * @version 1.0.1
 */
 /**
 * Changelog
 *
 * 1.0.1:
 * Created missing function
 * Updated comments in the class.
 *
 * 1.0:
 * Initial Release
 */
 
/**
 * Handles Rss in a more fasionable way.
 * @package Rss
 * @class RssGenerator
 */
class RssGenerator
{
    /**
    * @var array $mappings Maps database columns to Rss nodes.
    * @access private
    */
    var $mappings = array('guid'=>'','link'=>'','description'=>'','title'=>'','pubDate'=>'','category'=>'','author'=>'');
   
    /**
    * @var array $channel Channel information
    * @access private
    */
    var $channel = array('title' => 'RSS Feed Generator','link' => '','description' => 'Feed generated by RssGenerator (http://www.daasor.info)','language' => 'en','pubDate' => '','lastBuildDate' => '','docs' => 'http://blogs.law.harvard.edu/tech/rss');
   
    /**
    * @var array $functionMap Maps database columns to Rss nodes using custom functions.
    * @access private
    */
    var $functionMap = array('guid'=>null,'link'=>null,'description'=>null,'title'=>null,'pubDate'=>null,'category'=>null,'author'=>null);
   
    /**
    * @var int $numRows Number of rows to get.
    * @access private
    */
    var $numRows = 15;
   
    /**
    * @var string $mysqlHost mySQL hostname (defaults to localhost)
    * @access private
    */
    var $mysqlHost = "localhost";
   
    /**
    * @var string $mysqlUser mySQL username
    * @access private
    */
    var $mysqlUser;
   
    /**
    * @var string $mysqlPass mySQL password
    * @access private
    */
    var $mysqlPass;
   
    /**
    * @var string $mysqlDatabase mySQL Database
    * @access private
    */
    var $mysqlDatabase;
   
    /**
    * @var string $mysqlTable mySQL table
    * @access private
    */
    var $mysqlTable = "";
   
    /**
    * @var string $mysqlTableIndexField mySQL table index field
    * @access private
    */
    var $mysqlTableIndexField = "id";
   
    /**
    * @var boolean $mysqlTablePubdateInt Is pubDate field int?
    * @access private
    */
    var $mysqlTablePubdateInt = false;
   
    /**
    * @desc mysql link
    * @access private
    */
    var $mysqlLink = null;
   
    /**
    * @var int $throwErrors (0/1/2) Decides whether errors should be thrown or not.
    * @desc 0 = Don't 1 = raise a user error
    * @access private
    */
    var $throwErrors = 0;
   
   
    /**
    * @desc class contructor
    */
    function Rss()
    {
        $this->channel['link'] = 'http://'.$_SERVER['HTTP_HOST'];
        $this->channel['pubDate'] = $this->formatDate(time());
        $this->channel['lastBuildDate'] = $this->formatDate(time());
        $this->mapFunction('pubDate',array(&$this,'formatDate'));
    }
   
    /**
    * @desc Formats date for rss feed
    * @access private
    * @param {int} $input Seconds since epoch
    * @return {string} formatted date
    */
    function formatDate($input)
    {
        return date('D, d M Y H:i:s O',$input);
    }
   
    /**
    * @desc Throws an error
    * @access private
    * @param string $str Error message
    */
   
    function throwError($str) {
        if ($this->throwErrors == 1)
        {
            trigger_error('RssGenerator: '.$str,E_USER_ERROR);
        }
    }
    /**
    * @desc Connects to the mysql database
    * @access private
    */
    function connect()
    {
        $this->mysqlLink = mysql_connect($this->mysqlHost,$this->mysqlUser,$this->mysqlPass);
        if ($this->mysqlLink)
        {           
            if (!mysql_select_db($this->mysqlDatabase))
            {
                $this->throwError('Could not select Database');
            }
        } else {
            $this->throwError('Could not connect to mySQL host.');
        }
    }
    /**
    * @desc Maps a column to a Rss node.
    * @access public
    * @param string $column mysql column name
    * @param string $node rss node name
    */
    function map($column,$node)
    {
        if (array_key_exists($node,$this->mappings))
        {
            $this->mappings[$node] = $column;
        } else {
            $this->throwError('Unknown node');
        }
    }
    /**
    * @desc Sets channel information
    * @access public
    * @param string $field Channel field to update
    * @param string $value new value
    */
    function setChannel($field,$value)
    {
        if (array_key_exists($field,$this->channel))
        {
            $this->channel[$field] = $value;
        } else {
            $this->throwError('Unknown channel field');
        }
    }   
    /**
    * @desc Maps a column to a custom function
    * @access public
    * @param string $node rss node name
    * @param mixed $function array/string function name or an array with class name and method name
    */
    function mapFunction($node,$function)
    {
        if (array_key_exists($node,$this->functionMap))
        {
            $this->functionMap[$node] = $function;
        } else {
            $this->throwError('Unknown node');
        }
    }
    /**
    * @desc Prepare value for the rss feed
    * @access private
    * @param string $node rss node name
    * @param string $value value from mysql table
    * @param int $row values for the row
    * @return string Prepared value for rss feed.
    */
    function prepareNode($node,$value,$row)
    {
        if ($this->functionMap[$node] != null)
        {
            return call_user_func($this->functionMap[$node],$value,$row);
        } else {
            return $value;
        }
    }
    /**
    * @desc Queries the database
    * @access private
    * @param string $query Query to execute
    * @return array results
    */
    function query($query)
    {
        if ($this->mysqlLink == null)
        {
            $this->connect();
        }
        $queryResults = mysql_query($query,$this->mysqlLink);
        if (!$queryResults)
        {
            $this->throwError(mysql_error());
        }
        $results = array();
        while ($array = mysql_fetch_array($queryResults))
        {
            array_push($results,$array);
        }
        return $results;

    }
    /**
    * @desc Set a setting in the class
    * @access public
    * @param string $setting Setting to update
    * @param mixed $value New value to set
    */
    function set($setting,$value)
    {
        if (isset($this->$setting))
        {
            if (is_array($this->$setting) || strtolower($setting) == "mysqllink")
            {
                $this->throwError('You are not allowed to update that value.');
            } else {
                $this->$setting = $value;
            }
        }
        else {
            $this->throwError('Property does not exist.');
        }
    }
    /**
    * @desc Builds the feed
    * @access public
    */
    function build()
    {
        // Create Document and Set encoding
        $document = new DOMDocument('1.0');
        $document->encoding = 'UTF-8';
       
        $root = $document->createElement('channel');
        // add the channel information
        foreach ($this->channel as $field => $value)
        {
            $tmp = $document->createElement($field);
            $tmp->appendChild($document->createTextNode($value));
            $root->appendChild($tmp);
            $tmp = null;
        }
       
        $fields = array('`'.$this->mysqlTableIndexField.'`');
        // builds field to select
        foreach ($this->mappings as $node => $field)
        {
            if ($field != '')
            {
                if ($node == 'pubDate')
                {
                    if ($this->mysqlTablePubdateInt == false)
                    {
                        $fields[] = "UNIX_TIMESTAMP(`".$field."`) `".$field."`";
                    } else {
                        $fields[] = "`".$field."`";
                    }
                } else {
                    $fields[] = "`".$field."`";
                }
            }
        }
        $fields = array_unique($fields);
        $fieldString = join(',',$fields);
        // Build query
        $query = sprintf("SELECT %s FROM %s ORDER BY %s DESC LIMIT %d",$fieldString,$this->mysqlTable,$this->mysqlTableIndexField,$this->numRows);
       
        $results = $this->query($query);
        if (is_array($results) && count($results) > 0)
        {
            $items = array();
            foreach ($results as $row)
            {
                $items[$object[$this->mysqlTableIndexField]] = array();
                $item = $document->createElement('item');
                foreach ($this->mappings as $node => $field)
                {
                    $items[$object[$this->mysqlTableIndexField]][$node] = $document->createElement($node);
                    $items[$object[$this->mysqlTableIndexField]][$node]->appendChild($document->createTextNode($this->prepareNode($node,$row[$field],$row)));
                    $item->appendChild($items[$object[$this->mysqlTableIndexField]][$node]);
                }
                $root->appendChild($item);
            }
        }
        $document->appendChild($root);
        header("Content-type: application/xml; charset=utf-8");
        echo $document->saveXML();
       
    }
       
}

?>


This should do for php4, if not, let me know.

22:02 updated
Last edited by Dandy on Fri Jul 04, 2008 8:36 pm, edited 1 time in total.
Dandy
 

Re: Rss feed generator

Postby Cristian » Fri Jul 04, 2008 8:27 pm

Thank you dandy, for your version 4, I'm sorry for my mistake.
Cristian
proof of advance
proof of advance
 
Posts: 282
Joined: Sun Nov 04, 2007 3:02 pm
Location: Denmark
Authnick: Sumsar


Return to PHP Release

Who is online

Users browsing this forum: No registered users and 2 guests

cron