mauricederegt Posted February 4, 2015 Share Posted February 4, 2015 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 Quote Link to comment https://forums.phpfreaks.com/topic/294385-edit-a-line-in-a-txt-file-containing-a-certain-word-id/ Share on other sites More sharing options...
requinix Posted February 5, 2015 Share Posted February 5, 2015 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. Quote Link to comment https://forums.phpfreaks.com/topic/294385-edit-a-line-in-a-txt-file-containing-a-certain-word-id/#findComment-1504921 Share on other sites More sharing options...
mauricederegt Posted February 5, 2015 Author Share Posted February 5, 2015 I agree, but a db is not an option atm Quote Link to comment https://forums.phpfreaks.com/topic/294385-edit-a-line-in-a-txt-file-containing-a-certain-word-id/#findComment-1504942 Share on other sites More sharing options...
CroNiX Posted February 5, 2015 Share Posted February 5, 2015 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>'; Quote Link to comment https://forums.phpfreaks.com/topic/294385-edit-a-line-in-a-txt-file-containing-a-certain-word-id/#findComment-1504971 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.