Check out the example page or download source code.

So that’s how it cooks:

1. Load the text file with the comments and convert it to an array with json_decode

/* get comments from file */
$commentsText = file_get_contents('comments.txt');

/* create array list from comments */
$commentsList = json_decode($commentsText,true);

2. Check if a new comment was posted and save to file when valid.

/* check if new comment is posted and minimum 3 characters are set */
if( !empty($_POST['comment']) && strlen($sComment) > 3 ){

        /* get posted comment and remove all HTML */
        $sComment = strip_tags($_POST['comment']);

        /* add comment, client IP and date to array */
        $commentsList['comments'][] = array(
                'text' => $sComment,
                'ip' => $_SERVER['REMOTE_ADDR'],
                'date' => time()
        );

        /* convert comments to string */
        $commentsText = json_encode($commentsList);

        /* save comment to file */
        file_put_contents($commentsFile, $commentsText);
}

3. Then we can loop the comment list and create HTML for the output

/* create html list */
$commentsHTML = "<ul>";
/* loop all comments */
foreach( $commentsList['comments'] as $commentItem ){
        // add comment to html list
        $commentsHTML.= "<li>" . $commentItem['text'] . "</li>";
}
/* close html comments list */
$commentsHTML .= "</ul>";

4. Then we add the HTML form and the list with comments

<form id="comments" method="POST"> <h1>Comments?</h2> <div><?=$errorMessage?></div> <textarea id="comment" name="comment" cols="70"> </textarea><br/> <input type="submit" value="yes" /> <?=$commentsHTML?>

I know simple but i thought to share it, you can see the full example including sorting and some more validation stuff, or check out the example page.

3 responses to “PHP Simple Comments Read/Write jSon data to text file”

  1. Brian Miller says:

    I found your blog while looking for a way to grab data from a json feed along with some form data and write the results to a text file to be used to create marker lists for the google map on my webpage. I don’t have the skills to do this. Would you be interested in helping.

  2. sofasurfer says:

    @Brian Check out my new post about dynamic maps. Hope this helps.

Leave a Reply to sofasurfer Cancel reply

Your email address will not be published. Required fields are marked *