How To Easily Add Comments to Your Website With PHP and XML

You will need three files

  • Comments.php – PHP class that will handle comments
  • postcomments.php – PHP script that will add new comments
  • page.php – where your comments and comment form will appear

Comments Handler Class

This class will have a private variable and three functions.

var $commentsFolder='comments';

public function post($pageID,$comment,$author);

public function show($pageID);
private function get($pageID);

Let’s go over what each of the functions will do.

  • post – add new comments
  • show – display comments
  • get – return comments variable to be used by show()

Handling New Comments

We will be storing comments in textfiles, each of this files will represent an article, page or any type of content in your site, all you need is to give a unique id to each piece of content.

Each comment in each file will be put inside its own <comment> tag and each tag will have an attribute for the author.

Example:

<comment author="someones name">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce odio leo, vestibulum non hendrerit varius, 
condimentum nec turpis. Suspendisse id lectus vitae nulla lobortis tristique.
Donec semper varius lorem at laoreet. 
Maecenas neque sapien, blandit nec pretium sit amet, adipiscing ac arcu. Mauris congue turpis ut tortor dignissim
scelerisque.
 Etiam rhoncus dapibus dolor, non pretium risus vehicula non.
</comment>

This is how our post function needs to look like.

class Comments
{
var $commentsFolder='comments';

	public function post($pageID,$comment,$author)
	{
		$file=$this->commentsFolder.'/'.$pageID.'.txt';
		
		$comment=htmlentities($comment,ENT_QUOTES,'UTF-8');
		$author=htmlentities($author,ENT_QUOTES,'UTF-8');
		
		$newComment="<comment author='{$author}'>{$comment}</comment>";
		
		file_put_contents($file,$newComment,FILE_APPEND);
		
		echo "
		<p>
		<fieldset>
		<b>Author:</b>{$author}<br />
		{$comment}
		</fieldset>
		</p>"
	}
}

Getting and Formatting Comments

Our comment files are not XML files because they are missing the XML header, they also need a main tag around all the comments. We can’t add this every time a new comment is posted, but we always do this later, this is purpose of the get() function, which will be called inside the show() function.

The get function:

	private function get($pageID)
	{
		$file=$this->commentsFolder.'/'.$pageID.'.txt';

		if(file_exists($file))
		{
		$comments=file_get_contents($file);
		$xml='<?xml version="1.0" encoding="UTF-8"?>
		<comments>
		'.$comments.'
		</comments>';
		
			return $xml;
		}
		else
		{
			return false;
		}
	}

Now that get has created an XML string we can use show() to format and display the comments.
Learn how to read XML with PHP

	public function show($pageID)
	{
		$comments=$this->get($pageID); // get() turns the comment files into an XML string.

		if($comments)
		{
			$xml=simplexml_load_string($this->get($pageID));
			
			foreach($xml->comment as $comment)
			{
				echo "<p>
				<fieldset>
				<b>Author: </b>{$comment['author']}<br />
				
				{$comment}
				</fieldset>
				</p>";
			}
		}
		else
		{
			echo 'No comments to show';
		}
	}

The Comment Form and Showing Comments:

Now that our comment class is ready we can build a comment form for articles on website. We will identify what comments we need to load via $_GET, but you can get values for the comment function anyway you want.

Our comment form will be simple but it will be "ajaxified" with JQuery.
Learn AJAX with JQuery

<?php
// include comments class
require_once "Comments.php";
// create comments object
$comments=new Comments();
// SANITIZE!!!
$pageID=$_GET['pageid'];
?>
<html>
<body>

<div id="content">

</div>

<p>
<label>Leave a comment:</label><br />
<label>your name</label><br />
<input type="text" id="author" /><br />
<textarea id="comment" rows="10" cols="50">

</textarea>
<input type="hidden" id="pageID" value="<?php echo $pageID;?>" />
</p>
<button id="post-comment">Post</button>

<div id="comments-box">
<?php
// show comments
$comments->show($pageID);
?>
</div>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
// set variables
var comment;
var author;
var pageID=$("#pageID").val();
var postUrl='postcomment.php';

	$("button#post-comment").click(function(){
		// get comment
		comment=$("textarea#comment").val();
		author=$("input#author").val();
		// send values to script
		$.post(postUrl,{pageID:pageID,comment:comment,author:author},function(response){
			// append new comment to comment textbox
			$("#comments-box").prepend(response);
			// clear comment textarea
			$("textarea#comment").val('');
		});
	});
	
});
</script>
</body>
</html>


Receiving the New Comment:

We are one step away from finishing this script, and this last script is short! All we need to do is get the POST data from our comments form and pass it to the comments class’ function post()

require_once "Comments.php";

$pageID=htmlentities($_POST['pageID'],ENT_QUOTES,'UTF-8');

$comment=new Comments();

$comment->post($pageID,$_POST['comment'],$_POST['author']);
blog comments powered by Disqus