Write To Existing File And Replace Only Specific Contents

Joined: 11/28/2008

I'm trying to read and write to an html file, but only a specific div.

CODE
<html>
<head>
</head>
<body>
<div id='notthediviwanttorewrite'>
This is NOT text to replace
</div>
<div id='somediv'>
This is text to replace
</div>
</body>
</html>

I have a script that outputs the content I want to replace, but I don't know how to rewrite ONLY that specific content. Any help is appreciated.

Joined: 11/28/2008
Use str_replace.You can

Use str_replace.

You can modify the HTML to get rid of the "div id somediv" with anything you want, like <!-- REPLACE --> and use that as the argument, or you can pass in the portion of HTML you need replaced if that is not possible.

~Andrew~

Joined: 11/28/2008
If the HTML is coded as

If the HTML is coded as XHTML, then you may be able to use DOMXML. The problem with using str_replace or even regular expressions is that it is difficult to do the right thing when you have nested DIV's.

Paul Davey
Whitford Church
"Everyone who calls on the name of the Lord will be saved." Romans 10:13
"For all have sinned and fall short of the glory of God, and are justified

Joined: 11/28/2008
bobbymac @ Oct 5 2007,
QUOTE(bobbymac @ Oct 5 2007, 06:15 AM)
If the HTML is coded as XHTML, then you may be able to use DOMXML. The problem with using str_replace or even regular expressions is that it is difficult to do the right thing when you have nested DIV's.

I've actually figured out a good way of doing it. I use php's explode function. Things are coming along nicely with my project. It's a database-less CMS, and it uses either FCKeditor or another editor called tinymce too. The problem with FCKeditor seems to be that it isn't supported by Safari, which is the browser of my client. Tinymce works on Safari, but is a bit clunky. Check out my current tinymce code:

CODE
<?php session_start();
//works in windows safari, which is a bonus compared to the current version of FCKeditor
?>
<html>
<head>
<style type="text/css">
    #editbox, #editbox2 { width:500px; height:200px; }
</style>
<script language="javascript" type="text/javascript" src="tinymce/jscripts/tiny_mce/tiny_mce.js"></script>
<script language="javascript" type="text/javascript">
tinyMCE.init({
    mode : "textareas",
    theme : "advanced",
    theme_advanced_buttons1 : "bold,italic,underline,link,unlink",
    theme_advanced_buttons2 : "",
    theme_advanced_buttons3 : "",
    theme_advanced_toolbar_location : "top",
    theme_advanced_toolbar_align : "left",
    extended_valid_elements : "a[name|href|target|title|onclick]"
});
</script>
</head>
<body>
<?php
//Simple Content Management in PHP Without Database Access
//from http://www.sitecritic.net/articleDetail.php?id=188 by Bernard Peh, 2006-07-12

/*
A Content Management System (CMS) allows you to update your website easily without touching anything
in the backend. If you are a non-IT person, you will almost always want a CMS for your website because
it makes you less dependent on your web designers or developers to add, edit or delete contents in your website.

There are many good CMS out there but most of them require some sort of database access in the backend.
Many PHP CMS uses mysql or postgres database which resides in the server. Installation and troubleshooting
of CMS might require some technical knowledge and server configuration which could be daunting for some.

I was creating a website for a client recently when he requested a CMS for him to update the web pages
during his free time. I was tempted to install a popular ready made CMS such as joomla but on futher thoughts,
joomla on a small business website could be an overkill. The website would most likely not utilise many features
of joomla and furthermore, his hosting package does not include a database. Given a short time frame to come
up with a solution, I created a simple PHP script for him to do the job, ie to edit the content of a few web pages only.

In this tutorial, we are going to create a simple CMS in PHP without the use of MYSQL, POSGRESQL or any other databases.

Simple Login Form

In a form, I added 2 fields, the username and password. The form is to post its data back to the same page so
that we can verify whether the username and password fits with a preset value. The html code for the form is shown below:
*/
?>
<form method="post" action="">
  <table width="400"  border="0" align="center" cellpadding="2" cellspacing="2">
       <tr>
      <td>Username: </td>
      <td><input type="text" name="username"></td>
    </tr>
    <tr>
      <td>Passwd: </td>
      <td><input type="password" name="passwd"></td>
    </tr>
    <tr>
      <td> </td>
      <td><input type="submit" name="Submit" value="Submit">   <input type="reset" name="reset" value="Reset">
</td>
    </tr>
  </table>
</form>
<?php
/*
Once the username and password are verified, a username session will be triggered to remember
that the administrator has logged into the system. We will prompt the user if they enter the wrong details.
*/
if ($_POST['logout'] == '1'){
    unset($_SESSION);
}

if (isset($_POST['Submit'])) {
    if (($_POST['username'] == 'admin') && ($_POST['passwd'] == 'yourpassword')) {
        $_SESSION['username'] = 'login';
    }
   else {
       echo "<b>You login details is not correct. Pls login again</b>";
    }
}
/*
If everything goes well as expected, a quick menu will be displayed. The menu consists of a few links to the files that are editable.
In this case, the links are pointing to the home and contact us page. There is also a link to logout from the system.
*/
if ($_SESSION['username']=='login') {
    echo "    
    <form method='post' action=''>
        Choose File to Edit:   <select name='file'>
            <option value='cms_edit.htm'>cms_edit.htm</option>
            <option value='cms_edit.htm'>cms_edit.htm</option>
            <option value='cms_edit.htm'>cms_edit.htm</option>
        </select>
        <input type='submit' value='go'></input>
    </form>
";
}
/*
Creating Start and End Points in the HTML Files

Before we can start editing the content, we have to tell the CMS which part of the content is editable. In order to do that,
we need to create a unique marking in the HTML file. The HTML code for my home page may look like this:

<html>
    <body>
        <div class='header'>
        This is my header
        </div>
        <div class='main'>
        Contents written here can be edited
        </div>
    </body>
</html>

If I want all the contents within the <div class='main'> to be editable, I need to add my own unique code just for
the sake of marking the editable region. So the new HTML code might look like this:

<html>
    <body>
        <div class='header'>
        This is my header
        </div>
        <div class='main'>
            <!-- EDITABLE -->
            Contents written here can be edited
             <!-- EDITABLE -->
        </div>
    </body>
</html>

The Decoding Engine

What we have done in the previous step is really to encode the HTML file with the <!-- EDITABLE --> tag.
We now need to decode it. Thanks to the PHP explode function, we can now strip out the <-- EDITABLE --> tag and get the contents.
*/
if (isset($_REQUEST['file'])) {
    $fc = file_get_contents($_REQUEST['file']);
    $text = explode("<!-- EDITABLE -->",$fc);
    echo "<p>Edit contents of the  \"first-content\" div here:<br />";
    echo "<form method='post' action=''><textarea name='content' id='editbox'>$text[1]</textarea></p>";
    echo "<p>Edit contents of the  \"second-content\" div here:<br />";
    echo "<textarea name='content2' id='editbox2'>$text[3]</textarea></p>";
    echo "<p><input type='hidden' name='file' value='".$_REQUEST['file']."' />
<input name='submitUpdate' type='submit' value='Update Page'></form>";
}
/*
The variable $text is an array. $text[0] and $text[2] corresponds to the content before and after
the tag <!-- EDITABLE -->. Therefore $text[1] is the editable text we want and we display it in the textarea.

Capturing the Edited Content

The edited content is passed again back to the same page via the $_POST variable. If the submit button has been
clicked, we will update the home page content. The way we do it is similar to how we strip the <!-- EDITABLE --> tag using
the explode function. Because we are actually writing to a file, not to a database, we need not add escape characters to
the content. PHP version 4.x has magic_quotes turned on by default which happens to escape all our $_POST variables.
So if magic_quotes is turned on, we need to unescape the $_POST variables.
*/
if (isset($_POST['submitUpdate'])) {
    if (get_magic_quotes_gpc()) {
        $_POST = array_map('stripslashes',$_POST);
    }

   $fc = file_get_contents($_POST['file']);
   // truncate file
   $fw = fopen($_POST['file'], 'w+');
   $text = explode("<!-- EDITABLE -->",$fc);

   $newText = $text[0]."<!-- EDITABLE -->".$_POST['content']."<!-- EDITABLE -->".$text[2]."<!-- EDITABLE -->".$_POST['content2']."<!-- EDITABLE -->".$text[4];
   if (fwrite($fw, $newText)===FALSE) {
      die("Cannot write to file.");
   }
   fclose($fw);
   exit("<div><span class='redText'>The file has been updated.<br /><br />
              <form method='post' action=''>
        Click here to logout <input type='hidden' name='logout' value='1'></input>
        <input type='submit' value='log out'></input> or choose another file to edit at the top of the page.
    </form></div>");
}
/*
In the function "file_get_contents", we get the contents of the file to be edited and strip them
into 3 parts again. Noticed that I need to clear my original file with a fopen($_POST['file'], 'w+').

Now, we rejoin the 3 parts back again. Our edited content is actually in $_POST['content'] but it might
consists of some illegal characters which has certain meaning in PHP. So we need to convert them into
the HTML equivalent using the htmlentities function. We then close the file.

The codes may seem complicated but the logic should be simple enough. One thing to note though is that
the content is displayed in a textarea. This means that the user has to put in their own html tag such as
<b>, <p> ...etc if they want any text formating. You can also add in a HTML editor to make the text formatting
easier. I actually used fckeditor with this content management system in my client's website.

The full source code at my website - PHP CMS.

Conclusion

This method of editing content is not new. I noticed that many article or dynamic sites actually use similar
method for editing their website content. I guess this system might work for small websites and that you don't
need extra features such as the ability to customise the menu. If you want more features, you will need a better CMS.

If you are writing one CMS for yourself that allows much more customization such as the ability to edit headers,
menus, footers, css, templates..etc, I would not recommend the approach in this tutorial because I am using a procedural
coding technique (You might have already noticed that I actually cramped all the codes in one page).
In other words, it is better to do it in the object oriented way.

In conclusion, this simple CMS allows you to edit your content quickly without the need
for database access. Modifications can also be done to the source code easily.
*/
?>
</body>
</html>

Joined: 11/28/2008
Well done, that is a good

Well done, that is a good idea.

You could do this line a little differently:

CODE
$newText = $text[0]."<!-- EDITABLE -->".$_POST['content']."<!-- EDITABLE -->".$text[2]."<!-- EDITABLE -->".$_POST['content2']."<!-- EDITABLE -->".$text[4];

perhaps like this:

CODE
$text[1] = $_POST['content'];
$text[3] = $_POST['content2'];
$newText = join('<!-- EDITABLE -->', $text);

I would also define '<!-- EDITABLE -->' as a PHP constant so you never mist-type it and can change it globally.

Paul Davey
Whitford Church
"Everyone who calls on the name of the Lord will be saved." Romans 10:13
"For all have sinned and fall short of the glory of God, and are justified