Jump to content

Recommended Posts

Hi all,

 

I have the following code to add a new line in a text file:

if(!empty($name)){
$fp = fopen($croom."_test.txt", 'a');  
     fwrite($fp, '<div id="'.$id.'"><b>'.$name.'</b>: '.$msg.'<br/></div>'.PHP_EOL);  
    fclose($fp);   
}
Everytime this is executed, the text file will grow like this:
<div id="234"><b>Jake</b>: blabla<br/></div>
<div id="345"><b>Sam</b>: sfsfe<br/></div>
<div id="234"><b>Jake</b>: yyujyuj<br/></div>
<div id="098"><b>Bob</b>: bnhngn<br/></div>
In time this text file will grow huge. I want to prevent this by overwriting the line containing a certain word/ id (lets say: 234)
 
In the example above you see that Jake is in there twice, this should not be allowed. The second line from Jake should overwrite the first line from him, so each id has just 1 line of text in the text file.
 
How to do this? How to edit my code above to achieve this? Hope anyone can help.
 
Many thanks
 
A coding newbie :)

Store the information in a database instead of generating HTML in a file.

 

Otherwise you'll have to read in the entire file, locate the Jake line, replace the new entry with the old one, and write the contents back out. That sucks. With a database you store all the information in there that you want, update however you want and whenever you want, then when you need that HTML you run a query to get the data back out and format however you want.

I still wouldn't store as HTML, especially if you're searching for things in the file. That will complicated things.

 

I'd store like:

234::Jake::blabla

 

Then when looping through lines of the file, you could:

list($id, $name, $text) = explode('::', $file_line);

if ($id == '234') //we already have 234

or for output back into HTML

echo '<div id="' . $id . '"><strong>' . $name . '</strong>: ' . $text . '<br/></div>';
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.