Diary of A Webmaster Part 2 – Create a Content Feed

    Mitchell Harper

    So, you’ve spent the better part of a year creating your PHP/MySQL driven Website. You’ve got a reasonable amount of decent, flexible content, and you’re buddies with a couple of other Webmasters, so they’ve given you a free banner ad on their site in exchange for one on yours. What else can you do to promote your pièce de résistance?

    A site’s promotion can be even more difficult than its development. I’ve found that one of the best ways to attract more visitors to your site is to share your content with whoever wants it. That’s right; let them publish your articles on their site (as long as they add a link back to your site near the end), write articles specifically for other Websites and ezines (hey, I’m doing that now aren’t I?), and set up a content feed from your site.

    Just last week I set up a content feed similar to the one I’ll describe in this article. What’s that you say? "How do I set up a content feed? I only know PHP and MySQL!" Never fear — in this article I’ll show you how easy it is to set one up. But first, let’s discuss why you’d want to set up a content feed for your site.

    Why A Content Feed?

    I’ve said it before and I’ll say it again: if your site’s going to succeed on the Net, it needs to contain useful, free content targeted directly at a niche market.

    Take a look at some of the most popular sites on the Web: ZDNet, Slashdot, Cnet, MoreOver, etc. All of these sites provide dynamic content feeds that anyone can use on their site, so that if I wanted to display their recent news headlines on my site, I would simply have to fill in a form and paste some HTML tags on my site, and I’d be done.

    If Joe Bloggs posts the HTML code for ZDNet’s content feed on his site, then it’s a win-win situation: Joe provides valuable news to his visitors, which keeps them coming back on a daily basis, and ZDNet benefits from increased traffic when Joe’s visitors click on the news headlines to see the full story on their site.

    A few reasons why you should consider creating your own content feed include:

    • It’s one of the best forms of free advertising.
    • Once other people post your content feed on their site, each headline actually links back to the full article your site. As many of you will know, the more links you have back to your site from other sites, the higher search engines such as Google will position you in their rankings.
    • Obviously, having others post your content feed on their site will boost your traffic. By how much your traffic will increase depends on the quality of your content and how well you formulate your headlines.

    Hopefully by now I’ve convinced you to set up a content feed. Let’s take a look at creating a sample content feed using some PHP and a MySQL database.

    Creating a Sample Content Feed

    One of the reasons why content feeds are so popular is because 99% of the time, all you need to do to include someone else’s content feed on your site is add a reference to an external JavaScript file using a HTML <script> tag, like this:

    <script language="JavaScript" type="text/javascript"  

    Let’s assume that I run a small Website and want to publish Joe Bloggs’s content feed on my site using the code above. In it, I’ve set the src attribute to a file named feed.php on Joe’s Website (and not a typical JavaScript file that ends with .js).

    This isn’t a problem, however, because both IE and Netscape don’t care what the file extension is, provided that, when the file is grabbed, it actually contains valid JavaScript code. Let’s create a sample content feed now. To start with, load the MySQL console application and create a new database named content:

    create database content; 
    use content;

    Next, create a new table named articles. This table will contain all our news items:

    create table articles 
     articleId int auto_increment not null,
     title varchar(100),
     content text,
     primary key(articleId)

    The table we’ve just created should be pretty self-explanatory. It contains three fields:

    1. articleId, an integer which is also a primary key and unique identifier,
    2. title, which will contain the headline of each news item, and
    3. content, a text field that will contain the body of each news item.

    Let’s add three news items to our articles table using these MySQL commands:

    insert into articles values(0, 'PHP scripting language takes  
    world by storm', 'It was announced today that at least two  
    million web sites around the world are using the PHP and  
    MySQL language/databasing technique to create  
    sites that are flexible');

    insert into articles values(0, 'Linux includes G++ compiler',  
    'Linux, one of the world's most popular operating systems,  
    also includes a copy of both the GCC and G++ compilers, which  
    allow you to compile C/C++ program easily from the  
    command line');

    insert into articles values(0, 'Microsoft announces C#',  
    'Microsoft have today announced that its new .NET framework  
    will be based around a language named C# (pronounced  
    C-Sharp). This language is much like C++ but is designed  
    for modern prorgammers');

    Next, we want to create the PHP script that will retrieve the news from our MySQL database and output it to the browser so that it appears as a bunch of JavaScript code. The PHP script’s name is feed.php and it’s available for download here. We’ll concentrate only on the more important aspects of the script.

     header("Content-Type: text/javascript");

    The first thing the script must do is declare that it will send out JavaScript code, as opposed to HTML. By default, PHP identifies the type of the output with a Content-Type: text/html header. To ensure that this script’s output is identified as JavaScript, however, we must set the header ourselves.

     $db_server = "localhost";  
    $db_db = "content";  
    $db_user = "admin";  
    $db_pass = "password";

    To begin, our script creates four variables that will be used to log in to our MySQL server. I’m assuming that MySQL is installed on the same machine on which the feed.php script will be set up.

     $sConn = @mysql_connect($db_server, $db_user, $db_pass);  
    $dConn = @mysql_select_db($db_db, $sConn);  
    if(!$sConn || !$dConn)  
      document.write("Couldn't load news");  

    Next, we use these four variables to connect to our MySQL server and select the content database. We add the "@" symbol to the beginning of the mysql_connect and mysql_select_db function calls. This tells PHP not to write any connection errors to the browser. This is important in our script, because we only want it to return valid JavaScript code.

    If either the mysql_connect or mysql_select_db commands fail, then $sConn or $dConn will contain no data. We use an if control to check for this, and if either one of them failed, we output document.write("Couldn't load news"); to the browser.

    document.write is a JavaScript function. It takes one argument and outputs the contents of that argument directly to the browser.

    Using a PHP script to output JavaScript may seem a little strange at first, but remember what I said earlier. All the user needs to do is set up a <script> tag whose src attribute references our feed.php file. As long as it returns JavaScript code, the browser will process it in the same way as it would inline JavaScript.

     $nResult = mysql_query("select articleId, title from articles order by  
                            articleId desc limit 10");

    Using the mysql_query function with a select statement returns the articleId and title fields for the ten articles most recently added to the articles table. The limit keyword makes sure that only ten are returned.

    To actually output the news headlines as part of a HTML table, we use a PHP while loop and output several calls to JavaScript's document.write function to build the table's rows, like this:

     while($nRow = mysql_fetch_array($nResult))  
      document.write('  <td>');  
      document.write('  <a target="_blank"  
      document.write(' </td>');  

    There's nothing special about this while loop. It uses PHP's mysql_fetch_array function to retrieve the next record from the $nResult result set and outputs a table row that contains a hyper-linked news headline.

    The actual URL of each headline points to http://www.jb-news.com/news.php and includes the ID of the article tacked onto the end. You can change that URL to a script on your PHP server and display the news based on the value of the newsId query string value. That's outside the scope of this article, however.

    One important thing to note about the code inside the while loop is that it uses PHP's addslashes function to convert any single quotes in the title to escaped single quotes by adding a backslash to them. If we were to output an un-escaped quote as part of the argument to document.write, then when that code was processed by JavaScript, it would assume that the quote marked the end of the argument, causing a JavaScript syntax error.

    Sample output for one of the news items using the while loop looks like this:

    document.write(' <td>');  
    document.write(' <a target="_blank"  
    >Microsoft announces C#</a>');  
    document.write(' </td>');  

    That's actually all we need to do to create a content feed from our sample MySQL database. Let's now set up the content feed and test it in our browser.

    Testing Our Content Feed

    To test our content feed is simple. First, make sure that the feed.php script is in a directory within your Web server's document folder structure. Next, create a new HTML file named test.html and save it in the same directory as the feed.php script (I'll assume that you've saved them both in the /php subdirectory of your Web server's root directory). Enter the following HTML into test.html:

    <title> Joe Bloggs News Test </title>  
    <body bgcolor="#FFFFFF">  
    <h1>The Latest News</h1>  
    <script language="JavaScript" type="text/js"  

    Run test.html in your Web browser. Assuming you used our sample feed.php, which contains additional code to format the results, the page should look something like this:


    If you have a registered domain name (such as mysite.com) that points to a Web server running PHP and MySQL, then try to create the content database on that server. Upload the feed.php script too. While keeping the test.html file on your local machine, replace its src attribute to point to the feed.php script on your Web server. Then run test.html in your browser -- it should appear exactly as before.

    What makes our content feed dynamic?

    Many things. The fact that we have complete control over the feed.php script on our server means that we may change anything we like in it (e.g. to include a sponsor's ad). Any sites that already use our content feed won't have to do a thing to get the updated version, because it's retrieved from our server every time it's displayed on their site.

    Also, whenever we add a new item to our articles table, it will appear at the top of the content feed. Let's try adding one now. Using the MySQL console application, enter this query:

    insert into articles values(0, 'MySQL Version 4 Released', 'Today,    
    MysQL AB have released MySQL version 4. It comes packed with a number    
    of new features including transactions and faster    
    query execution plans');

    Return to your browser and hit the refresh button; notice the new entry in the list of news stories:


    It's just as easy to remove items from our content feed using the MySQL delete command:

    delete from articles where articleId < 3;

    This would remove those articles whose articeId was less than three, thus leaving two news headlines in our feed:


    So, as you can see, using the <script src="..."> method to include the JavaScript generated by our feed.php script in other sites' pages ensures that any new records we add will automatically be visible in the content feed when it's displayed.


    Take the sample content feed described throughout this article and modify it to match the look and feel of your site. You'll also need to modify the MySQL queries to extract the right fields from your database.

    Once you've customised the script for your needs, tell everyone about it: your ezine subscribers, friends, other Webmasters, etc. You'll be amazed by how many of them will agree to post it on their site because it's so simple to do.

    Remember, all that anyone needs to do to get your content feed is include HTML code similar to the following (with the URL of your feed.php file, of course) in any page of their site:

    <script language="JavaScript" type="text/javascript"