Rockin’ RSS with PHP on your HTML

October 2, 2008


An RSS feed lets webmasters tease visitors into returning to their websites again and again to check out new content. Danny Wall explains how to set up this simple, automated, spamless way of getting Web surfers to come back for more.

While you may have a good grasp of RSS and what it is, stick with me for just a second and after we run over some preliminary stuff, we’ll move into creating an RSS feed of your own, for your website, using PHP.

RSS (which stands for Really Simple Syndication) is, at its core, a push technology that was developed by Netscape. It gives webmasters the ability to do two things: the first is to easily add content from other websites to their own, and it also easily allows webmasters to push their own unique content out to other people and other websites.

The use that will probably be the most exciting to you is that people who are sick and tired of the mountain of spam filling their inboxes, and tired of having to surf to dozens of sites to get the information they want, are turning to RSS–or more specifically an RSS reader, to obtain news and information on the latest updates to the blogs they follow. An RSS reader (such as the one that can be found at http://www.pluck.com) allows people to see all of the sites they follow in one convenient place and quickly and easily see if there’s anything new–and even what is new.

You can almost think of it as turning the Web into an email application, but without all the spam–because it lets you see which sites have new information in almost the exact same way you know if you’ve read an email or not.

This means that you can add new content to your site, and all of your visitors will know the content has been added and will know what was added. It also means that your own site content can be syndicated across the Web, driving traffic from a huge number of sites directly into your own.

An idea that’s catching on

This concept is so powerful that it is now being picked up and used by the largest players in the Internet news space such as Yahoo!News. It is also used by many blogging services such as Google’s recently acquired Blogger (actually, it uses Atom, but it is essentially the same thing) to keep their loyal readers up to date with new additions to the blogs.

In other words, the format is growing in leaps and bounds, driven not only by the biggest sites on the Web, but also by the cultural wildfire known as the blogosphere.

In the old days, when a Web site had a new update they wanted people to know about, it meant sending out an email, or using an email newsletter. The problem is that in today’s day and age, with many people getting hundreds of spam messages a day, people are block deleting much of their email–including messages they actually asked to receive.

Now, with RSS, it is possible to simply update your website, and the RSS readers that people have installed will automatically tell them an update has happened, what the update was, and give them the ability to quickly and easily surf to your site. No more email, no more worrying if the email you sent even reached the person.

Further, all of that doesn’t even count the ability for other webmasters to add your content to their site with no muss and no fuss (again, syndicating your content across the web).

How–and why–to get started

You should know that there are a lot of tutorials and the like on how to add RSS content to your own site. An excellent one can be found at: http://www.devshed.com/c/a/PHP/Plugging-RDF-Content-Into-Your-Web-Site-With-PHP.

Additionally, there are a wide range of tools to make adding RSS to your site easy with hardly writing any code of you own. I personally use the MagpieRSS toolset created in PHP which can be found at http://magpierss.sourceforge.net. So instead of covering how to get RSS added to your site, what I’d like to do is talk about how you can build your own RSS feed.

Some webmasters that I know groan over the thought of RSS. It’s yet another new technology to learn, another new thing to add to their site and manage. The thing is, RSS is really nothing more than an XML application, and if done right, it doesn’t need any management. Everything can be (indeed, should be) automated.

In fact, RSS it is the first widespread use of XML. It is the first time XML is being used to do something useful for the average Web surfer AND for the average webmaster.

To start with, the easiest thing to do will be to take a look at what an RSS file looks like. You can see an example RSS file at: http://www.wolfdatasystems.com/rss.xml

To anyone with any knowledge of HTML it isn’t really hard to figure out what is going on. There isn’t anything strange or scary, there isn’t anything to make you cringe.

Starting with the header

In fact, using the magic bag of tricks known as PHP, your own RSS file can be automatically created with very little effort, and once the PHP script is finished, the whole thing is “maintenance/management free.”

To provide a little further clarification, we’re going to cover the basics of RSS file creation (indeed, the example file I gave you above is only a basic RSS document). In future articles we’ll talk about other elements to the RSS specification, what they mean, and why you might want to use them (and I’ll provide you the additions to the PHP script you’ll get in this article to add those elements).

For nearly every website, some of the information in the RSS file–lets call it the “header” info–will be the same/static each time the file is created. That info is:

<?xml version=’1.0′ ?>
<rss version=’2.0′>
<channel>
<title>Wolf Data News</title>
<link>http://www.wolfdatasystems.com/</link&gt;
<description>News for programmers, business, and home computer users.</description>
<language>en-us</language>
<docs>http://www.wolfdatasystems.com/rss.xml</docs&gt;

As you can see, this amounts to the very first group of information in the file; and obviously you’ll want your own titles, your own links, and your own “feed description,” but the above will almost certainly be static information in your feed. Every day when my site updates the RSS file, this information is unchanged.

Now, lets go into building the PHP script to create the RSS file. For the sake of discussion, lets call this file create_rss.php:

<?php
// open a file pointer to an RSS file
$fp = fopen (“rss.xml”, “w”);

// Now write the header information
fwrite ($fp, “<?xml version=’1.0′ ?><rss version=’2.0′><channel>”);

fwrite ($fp, “<title>Wolf Data News</title>”);

fwrite ($fp, “<link>http://www.wolfdatasystems.com/</link>&#8221;);

fwrite ($fp, “<description>News for programmers, business, and home computer users.</description>”);

fwrite ($fp, “<language>en-us</language>”);

fwrite ($fp, “<docs>http://www.wolfdatasystems.com/rss.xml</docs>&#8221;);

So far, we haven’t done anything too challenging. All we’ve done is opened a file, and written the header information that won’t be changing from file creation to file creation.

As you can see, I have broken the header file writes into several pieces. I’ve done this simply to make the script easier to see instead of having stuff trailing off to the right side of notepad forever. It isn’t at all necessary, but I do recommend it simply to make it easier to modify the file in the future.

Adding content

At this point, you now need to begin adding the “item” level information; which is simply the content that has been added to your site. Before we get started on this, there are some things you need to know.

Generally, an RSS feed contains not only the most recently added content to your site, but quite a bit of “back” content as well. This is to allow any new users to not only see the most recent additions, but also see what has been done before they picked up your feed. This way, they’ll easily be able to look at that as well.

It’s a good thing for the new user, and for you, as often a person that picks up a new feed will spend some time checking out a lot of the “past” content and catching up on what you’ve got going.

That means we need to do two things.

First, you need to database your new content. In otherwords, you should be adding new content to your database, and your website should be pulling that new content out of the database. This will allow you to utilize PHP with maximum benefit and speed to build the RSS file.

$db = mysql_connect(“localhost”,”your_db_uid”,”your_db_pw”);
mysql_select_db(“db_name”,$db);
$content_sql = “select * from content where page=’index’ order by id desc”;

Obviously in the above line, you are seeing how I do it. Your query may be different depending on how you are databasing your content.

$content_result = mysql_query($content_sql);

So far, we’re still in the “basic” neck of the woods. In fact, all we need to do now is pull the content out of your site and put it into the RSS file.

while ($content_rec = mysql_fetch_row($content_result)) {
fwrite ($pd, “<item>”);

$headline = $content_rec[0];
$content_1 = substr($content_rec[1], 0, 250);
$content = strip_tags($content_1);
if (strlen($content_rec[1]) > 250) {
$content = $content . “….”;
}
fwrite ($fp, “<title>$headline</title>”);
fwrite ($fp, “<description>$content</description>”);
$item_link = “http://www.wolfdatasystems.com/index.php?d=$content_rec%5B3%5D&#8221;;
fwrite ($fp, “<link>$item_link</link>”);

fwrite ($fp, “</item>”);
}

Tease the reader

And essentially that’s it. Notice how I did NOT put the entire content into the RSS feed. You can put the entire content into the file if you want. Personally, I don’t recommend doing this. Instead, put just enough to tease the reader so that they want to visit your site.

Now, you will note that I do move the data around just a bit to not only shorten the length of what I’m sending out on the feed, but also to add the ellipses to let readers know there is more.

And again, how you decide to database your content will affect exactly how you pull that content out.

Anyway, at this point, all we need to do is close off the file.

fwrite ($fd, “</channel></rss>”);
fclose ($fd);

?>

It is a simple enough process. You can now have that ran by a cron job, or simply run the php file from a browser once a day.

Again, if you are running some sort of a content management system (and I’ll talk about how to easily build your own in future articles), creating the RSS file is obviously a simple matter of writing the static “header” information for your site/feed, pulling the content out of the database, writing each item of new content between “<item>” tags, and then closing the file off with the ending tags.

You may want to add in some other information into this feed, and again, we’ll also talk about what other information there is to add, and why you may want to put that into the feed. We’ll also talk about, if you are adding content via RSS feeds to your site, how to make THAT content from that OTHER feed a part of your own RSS feed. This will ensure that you’ve got a constantly updating RSS feed so that people will want to keep coming back to your site, driving up traffic, unique visitors per day, and page views per visitor.

Source: http://www.devshed.com/c/a/PHP/Rockin-RSS-with-PHP-on-your-HTML/

Advertisements

PHP RSS Parser

October 2, 2008


PHP RSS Parsers are what many PHP developers looking for these days as every web application or website has some RSS input or output.

RSS parsers make the use of RSS simpler as they have overcame the known RSS parsing difficulties.

WebResourcesDepot have collected the most popular free RSS Parsers coded with PHP:

SimplePie

SimplePie is a PHP code library that makes it very easy to use RSS & Atom feeds. SimplePie is fast and standards compliant as it supports:

  • RSS 0.90
  • RSS 0.91 (Netscape)
  • RSS 0.91 (Userland)
  • RSS 0.92
  • RSS 1.0
  • RSS 2.0
  • Atom 0.3
  • Atom 1.0

This PHP RSS parser class has also plugins for favorite web services.

lastRSS

lastRSS is also a simple yet powerful PHP class for parsing RSS feeds.

  • All RSS versions supported (0.9, 1.0 and 2.0)
  • Transparent cache (doesn’t cache RSS file directly, neither HTML output, but serialized variable; cached data isn’t parsed every time, but you can still access individual fields)
  • pubDate/lastBuildDate conversion to any date/time format
  • Character encoding conversion (all encodings supported by iconv library)
  • Returns an associative array with RSS fields
  • Regullar expression parsing (very quick)
  • Strips HTML from description (both hard-coded and entity-coded)
  • Optional limit the number of returned items
  • Two ways how to proceed CDATA information (get/strip CDATA content)

MagpieRSS
This PHP RSS parser class also supports well known feed formats like RSS 1.0, RSS 2.0 & Atom.

  • Easy to use
  • Parses most RSS formats
  • Integrated Object Cache
  • HTTP Conditional GETs
  • Configurable
  • Modular

Zend_Feed

Zend_Feed provides functionality for consuming RSS and Atom feeds. It provides a natural syntax for accessing elements of feeds, feed attributes, and entry attributes. Zend_Feed also has extensive support for modifying feed and entry structure with the same natural syntax, and turning the result back into XML. In the future, this modification support could provide support for the Atom Publishing Protocol.


My Final Assignment Report / Laporan Tugas Akhir (Skripsi)

February 7, 2008

This is my final assignment report in Bahasa Indonesia with title: TECHNIQUE TO PROTECT SOURCE CODE OF PHP APPLICATION WITH ENCRYPTION AND ENCODING METHOD. I hope this stuff will helps anyone who wants to create a final assignment report too. I do not provide any support for this report. Please use it as it is. 😉

Ini adalah laporan tugas akhir atau skripsi saya yang berjudul TEKNIK PROTEKSI SOURCE CODE APLIKASI PHP DENGAN METODE ENKRIPSI DAN ENCODING. Semoga bisa membantu bagi yang sedang menyusun skripsi. Saya tidak menyediakan support untuk laporan ini. Silakan gunakan sebagaimana adanya. 😉

http://rapidshare.com/files/89845515/fzn-ta08.zip


A Class With A Method

December 12, 2007

 

PHP is an Object Oriented Programming language. So, everything must defined in objects. This example will guide you to create class object.

<html>
<head>
<title>A Class with a Method</title>
<body>
<?php

// written by frozenade

class first_class{
var $me;
var $you;

function sayHello(){
print “hello <br />”;
$this->me = “this is me <br />”;
}
function sayHelloToo(){
print “<br />hello too <br />”;
print “you said: ” . $this->me;
$this->you = “and i see you”;
}
}

$obj = new first_class();

$obj->sayHello();
print $obj->me;

$obj->sayHelloToo();
print $obj->you;

?>
</body>
</html>


Create Class and Function in PHP

December 8, 2007

To create a professional-look programming, we need to create object source implemented in class and function.

This is a good tutorial to start learning about class and function environment in PHP.

Create an index file, name it main.php
Insert these into body section.

<form action=”<?php print(basename(__FILE__)); ?>?act=doit” method=”post”>
<pre>
Name : <input type=”text” name=”name” />
Age : <input type=”text” name=”age” />
</pre>
<input type=”submit” value=”Process” />
<input type=”reset” value=”Reset” />
</form>

<?php
if ($_GET[‘act’] == “doit”) {
include(‘class.php’);

if ($_POST[‘age’] < 20) {
$select->age1();
}
else {
$select->age2();
}

}

?>

Then create a file, name it class.php

<?php
// written by frozenade
// frozenade@bornmatic.com
// http://www.frozenade.co.nr

class operation {

function one() {
$var1 = $_POST[‘name’];
$var2 = “You are a teenager!”;
echo “Hello, $var1! $var2”;
}

function two() {
$var1 = $_POST[‘name’];
$var2 = “You are an adult!”;
echo “Hello, $var1! $var2”;
}

}

$op = new operation();

class selection {

function age1() {
global $op;
$op->one();
}

function age2() {
global $op;
$op->two();
}

}

$select = new selection();
?>

File class.php is an object file within class and function to be used in form processing.


How to Create Login Page in PHP and MySQL with Session

November 24, 2007

##########################
NEW UPDATE!!!
PHPMySimpleLogin 0.3

Download full source code:
http://rapidshare.com/files/404808631/phpmysimplelogin-0.3-frozenade.co.nr.zip.html
##########################

The production of login page using PHP and MySQL is actually very simple.

I assume that you use local web server connection (Apache and PHP) and your MySQL database configuration use ‘localhost’ as hostname and ‘root’ as username with blank password.
For this case, I recommend you to using XAMPP (http://www.apachefriends.org/en/xampp-windows.html).
Please download and install it to your path choice. e.g: C:\xampp

Run XAMPP Control Panel on desktop.

Start Apache and PHP modules.

Let’s create a database with PHPMyAdmin. Open your favorite browser, then type ‘http://localhost/phpmyadmin&#8217; at your browser address bar.

Create database ‘phpmysimplelogin’.

Click ‘Create’.

Now, let’s create a table, name it ‘user’ with ‘2’ (two) number of fields.

Click ‘Go’.

First field, name it ‘username’, type ‘varchar’, lenght/values ’25’.
Second field, name it ‘password’, type ‘varchar’, lenght/values ‘255’.

Click ‘Save’.

After that, we will fill the table. Click ‘SQL’ menu, then type this query on textbox:
INSERT INTO user (username, password) VALUES (‘admin’, md5(‘admin’))

Click ‘Go’.

It means, you fill ‘username’ field with string ‘admin’ and ‘username’ field with an encryption string of ‘admin’.
MD5 ia a function to create one-way encryption (hashing) from our password, so it can be more secure.
For detail, please check: http://www.php.net/manual/en/function.md5.php

Okay, now let’s prepare the web pages.
Create folder ‘phpmysimplelogin’ in your XAMPP’s htdocs. So, it will be ‘C:\xampp\htdocs\phpmysimplelogin’.
Remember to save all of your files you will create, inside this folder.

Run your favorite PHP code editor, e.g: PHP Expert Editor, RapidPHP, etc; or just Microsoft Notepad is fine.

Save document below with name ‘config.inc’.

<?php

$hostname = 'localhost';        // Your MySQL hostname. Usualy named as 'localhost', so you're NOT necessary to change this even this script has already online on the internet.
$dbname   = 'phpmysimplelogin'; // Your database name.
$username = 'root';             // Your database username.
$password = '';                 // Your database password. If your database has no password, leave it empty.

// Let's connect to host
mysql_connect($hostname, $username, $password) or DIE('Connection to host is failed, perhaps the service is down!');
// Select the database
mysql_select_db($dbname) or DIE('Database name is not available!');

?>

Next step, save document below and name it as ‘index.php’:

<?php

// Inialize session
session_start();

// Check, if user is already login, then jump to secured page
if (isset($_SESSION['username'])) {
header('Location: securedpage.php');
}

?>
<html>

<head>
<title>PHPMySimpleLogin 0.3</title>
</head>

<body>

<h3>User Login</h3>

<table border="0">
<form method="POST" action="loginproc.php">
<tr><td>Username</td><td>:</td><td><input type="text" name="username" size="20"></td></tr>
<tr><td>Password</td><td>:</td><td><input type="password" name="password" size="20"></td></tr>
<tr><td>&nbsp;</td><td>&nbsp;</td><td><input type="submit" value="Login"></td></tr>
</form>
</table>

</body>

</html>

As you see, there is ‘session_start();’.
This function is used to initializes a data session. It will creates a new session or continues previous session from data session changed by GET, POST or cookie.
See the detail information about session here: http://id.php.net/function.session-start

Now, prepare a file and give it name ‘loginproc.php’ to check the validity of username and password.

<?php

// Inialize session
session_start();

// Include database connection settings
include('config.inc');

// Retrieve username and password from database according to user's input
$login = mysql_query("SELECT * FROM user WHERE (username = '" . mysql_real_escape_string($_POST['username']) . "') and (password = '" . mysql_real_escape_string(md5($_POST['password'])) . "')");

// Check username and password match
if (mysql_num_rows($login) == 1) {
// Set username session variable
$_SESSION['username'] = $_POST['username'];
// Jump to secured page
header('Location: securedpage.php');
}
else {
// Jump to login page
header('Location: index.php');
}

?>

If username and password are correct, then we’ll be directed to ‘securedpage.php’.
This is the page that we want to show if login is successful. This page cannot be accessed if the correct data session is not found when login check is passed.
This page also contains ‘logout’ menu, so we can destroy our login data session then return to login page.

This is content of ‘securedpage.php’:

<?php

// Inialize session
session_start();

// Check, if username session is NOT set then this page will jump to login page
if (!isset($_SESSION['username'])) {
header('Location: index.php');
}

?>
<html>

<head>
<title>Secured Page</title>
</head>

<body>

<p>This is secured page with session: <b><?php echo $_SESSION['username']; ?></b>
<br>You can put your restricted information here.</p>
<p><a href="logout.php">Logout</a></p>

</body>

</html>

This is content of ‘logout.php’:

<?php

// Inialize session
session_start();

// Delete certain session
unset($_SESSION['username']);
// Delete all session variables
// session_destroy();

// Jump to login page
header('Location: index.php');

?>

Try on your favorite browser, ‘http://localhost/phpmysimplelogin/&#8217;.

So easy cake, isn’t it? 😉

##########################
NEW UPDATE!!!
PHPMySimpleLogin 0.3

Download full source code:
http://rapidshare.com/files/404808631/phpmysimplelogin-0.3-frozenade.co.nr.zip.html
##########################


GMail Contact List (Address Book) Grabber

August 27, 2007

Compared to the MSN and AIM contact grabbing classes interacting with Gmail was an absolute pleasure thanks to the hard work of at least two people truly deserving of thanks.

Y. H. Gan and Neerav Modi have produced an immensely powerful script for interacting with Gmail. It does far more than just grabbing the contact list. Using it feels a lot like using a swiss army knife or maybe one of those swanky Leathermans when a screwdriver will do just fine.

Grab the Script

The libgmailer script you’ll need can be downloaded from here. Grab that and then return for instructions on how to grab the contact list.

Grabbing the contact list

The code you need to retrieve the Gmail contact list with this script is as follows.

<?php

require_once("libgmailer.php");

$gmail_acc = "username";
$gmail_pwd = "acc_pass";
$my_timezone = 0;
$gmailer = new GMailer();
if ($gmailer->created) {
$gmailer->setLoginInfo($gmail_acc, $gmail_pwd, $my_timezone);

//uncomment if you need it
//$gmailer->setProxy("proxy.company.com");

if ($gmailer->connect()) {
// GMailer connected to Gmail successfully.
// Do something with it.

//Get the contacts
// For "Inbox"

$gmailer->fetchBox(GM_CONTACT, "all", "");

$snapshot = $gmailer->getSnapshot(GM_CONTACT);

//Outputs an array of the contacts
var_dump($snapshot->contacts);

//Outputs the number of contacts
var_dump($snapshot->contacts_total);

} else {
die("Fail to connect because: ".$gmailer->lastActionStatus());
}
} else {
die("Failed to create GMailer because: ".$gmailer->lastActionStatus());
}

?>

That’s it! It’s a bit more complex than for some of the other scripts but that’s what happens when you use such a powerful package for something simple. The only drawback with this script is that it requires CURL but I think most hosts have this installed so it’s unlikely to be a problem.

If you do have any problems though or want to give any other sort of feedback please post it in the comments of this thread.