• home
  • forum
  • my
  • kt
  • download
  • Creating Dynamic RSS Feeds with PHP and MySQL

    Author: 2007-08-24 19:17:28 From:

    In the very least bit of anything and everthing, you need to know the Basic syntax that exists with XML. XML is a very easy language to use/manipulate, seeing as how you can literally "make up" your own tags. Their are some set ones though that are highly useful for making RSS feeds.

    This is the basic body and syntax of the most basic RSS feed.

    <?xml version="1.0" encoding="utf-8"?>

    <rss version="2.0">

       <channel>

          <title>RSS FEED TITLE</title>
          <link>http://www.rssfeedwebsite.com</link>
          <description>Website Description</description>

          <language>en-us</language>
          <generator>PHP/$phpversion</generator>

              <item>
                <title>$title</title>
                    <link>$link</link>
                    <description>$mydescription...</description>
                    <pubDate>$pubDate</pubDate>
              </item>

        </channel>
    </rss>


    This is the utmost basic form of an XML document.

    each "element", or "item" in the feed needs to be started and stopped by <item> and </item>

    Please note, however, that the very first line "" needs to be at the very top of the document. If it is not at the very very top (first line before any output is started), the XML will throw an error.

    Ok, so now we know what the most basic syntax of an XML document is. Now what? Well, we can use PHP to dynamically generate any of the information that is related to it. The database calls and queries can all be accomplished within the same feed file. You can even call the feed and alter the way it displays things by changing the url query string to the feed.


    Lets pretend we have a animals database containing the data

    table news:
    news_id | news_title | news_category | news_author | news_content | news_date


    <?

    // prepare HTML text for use as UTF-8 character data in XML

    function cleanText($intext) {

        return utf8_encode(

            htmlspecialchars(

                stripslashes($intext)));

    }

     

    // set the file's content type and character set
    header("Content-Type: text/xml;charset=utf-8");

    // Connect to the database
    $db = mysql_connect('localhost','db_username','db_password');


    // Exit the script if the database can't be connected to
    if (!$db)
    {
       error_log("Error: Could not connect to database in rss.php.");
       exit;
    }

    // Select the database we will be pulling data from
    mysql_select_db('db_name');

    // run the query on the news table retrieving latest 10 topics
    $query = @mysql_query("SELECT news_id,news_title,news_category,news_author,news_content,news_date
                           FROM news ORDER BY news_date DESC LIMIT 0,9");
    if (!$query)
    {
        error_log("Error: Invalid Query made in rss.php");
        exit;
    }

    // Get the current version of PHP
    $phpversion = phpversion();

    // display RSS 2.0 channel information
    ECHO <<<END
    <?xml version="1.0" encoding="utf-8"?>
    <rss version="2.0">
       <channel>
          <title>RSS Title</title>
          <link>http://www.rsswebsite.com</link>
          <description>RSS Description</description>
          <language>en-us</language>
          <generator>PHP/$phpversion</generator>
    END;

     

    // loop through the array pulling database fields for each item

    while (list($id,$news_title,$category,$author,$summary,$date) = mysql_fetch_row($query)) {


       $title = cleanText($news_title);

       $link = "http://www.mynewssite.com/link/to/news_{$id}";

        // only retrieve a certain length of the content
       $description =  substr($summary,0,50);

     

       //Replace Ugly HTML that got into the Knowledgebase with nothing

       $desc_replace = array("<H3>&nbsp;</H3>", "<P>&nbsp;</P>", );

       $desc_replace_with  = array("", "", "");

       $desc_temp = str_replace($desc_replace, $desc_replace_with, $description);

     

       //Now clean the HTML

        // summary, cleaned up
       $mydescription = cleanText($desc_temp);

        // pub date (only if timestamp format is stored in database
        // otherwise you may want to remove the date() function.
       $pubDate = date("M d, Y",$date);

     

    // display each item.

    ECHO <<<END

      <item>
        <title>$title</title>
        <link>$link</link>
        <description>$mydescription...</description>
        <pubDate>$pubDate</pubDate>
      </item>

    END;

     

    }

     
    // Display end of RSS file data
    ECHO <<<END
        </channel>
    </rss>

    END;

    ?>


    Be sure to save this file as "rss.php". When you call it, you should get all the information that you brought out.

    I prefer to use the "list()" function when retrieving data from the database.

    You can, however still use $row = mysql_fetch_array(). Just adjust the code accordingly.

    Ok, well now we have our basic rss.php file. So now You want to adjust the content accordingly?

    No problem! All you have to do is use variables in the query and the query will take care of everything for you.

    The part of the code we will be manipulating is the code below:

    $query = @mysql_query("SELECT news_id,news_title,news_category,news_author,news_content,news_date
                           FROM news ORDER BY news_date ASC");


    Lets say we wanted to be able to adjust how many values are pulled through the querystring ie /rss.php?show=10

    So, we would set up the information through our superglobal $_GET

    // Show is set, use it
    if (isset($_GET['show']))
    {
        // Take the inputed variable and minus 1 (remember 0 counts as first record)
        // SECURITY: MAKE SURE YOU ESCAPE STRING
        $limitNumber = mysql_real_escape_string($_GET['show']) - 1;
    }
    else
    {
        // Make SURE you use else to catch all other instances let ssay if show is not set
        // Default to 10 records
        $limitNumber = 9;
    }


    Now our query will look like this:

    $query = @mysql_query("SELECT news_id,news_title,news_category,news_author,news_content,news_date
                           FROM news ORDER BY news_date ASC LIMIT 0,{$limitNumber}");


    you can now access your feed at /rss.php?show=10 will show 10 records while /rss.php?show=25 will show 25 records.


    What about changing the sorting? no problem again!


    if (isset($_GET['sort_by']))
    {
        if ($_GET['sort_by'] == "title_ASC")
        {
           $sort = "news_title ASC";
        }
        elseif ($_GET['sort_by'] == "title_DESC")
        {
           $sort = "news_title DESC";
        }
        elseif ($_GET['sort_by'] == "date_ASC")
        {
           $sort = "news_date ASC";
        }
        elseif ($_GET['sort_by'] == "date_DESC")
        {
           $sort = "news_date DESC";
        }
        elseif ($_GET['sort_by'] == "random")
        {
           // Randomly sort the data
           $sort = "RAND()";
        }
        else
        {
           // provide a default if sort_by is specified but not a correct value
           $sort = "news_date ASC";
        }  
    }
    else
    {
        // Default Sort Option via sort_by not being set.
        $sort = "news_date ASC";
    }



    With our combined SHOW and SORT_BY options we can now limit the number of results returned by the feed as well as how to sort it out accordingly.


    $query = @mysql_query("SELECT news_id,news_title,news_category,news_author,news_content,news_date
                           FROM news ORDER BY {$sort} LIMIT 0,{$limitNumber}");


    Lets say we wanted 15 random records:
    /rss.php?sort_by=random&show=15

    OR

    that we wanted the first 10 records ever published

    /rss.php?sort_by=date_DESC&show=10

    The possibilities are endless depending on what you program into your query!

    discuss this topic to forum

    relation tutorial

    No relevant information

    Category

      Ad Management (4)
      Calendars (3)
      Chat Systems (7)
      Content Management (6)
      Cookies and Sessions (8)
      Counters (8)
      Database Related (8)
      Date and Time (9)
      Development (6)
      Discussion Boards (7)
      E Commerce (6)
      Email Systems (9)
      Error Handling (5)
      File Manipulation (10)
      Flash and PHP (4)
      Form Processing (7)
      Guestbooks (8)
      Image Manipulation (3)
      Installing PHP (5)
      Introduction to PHP (9)
      Link Indexing (6)
      Mailing List Management (8)
      Miscellaneous (10)
      Networking (6)
      News Publishing (6)
      OOP (8)
      PEAR (6)
      PHP vs Other Languages (2)
      Polls and Voting (5)
      Postcards (0)
      Randomizing (8)
      Redirection (8)
      Searching (6)
      Security (6)
      Site Navigation (7)
      User Authentication (10)
      WAP and WML (7)
      Web Fetching (0)
      Web Traffic Analysis (11)
      XML and PHP (0)

    New

    Hot