etrader Posted May 26, 2011 Share Posted May 26, 2011 I append a string to a file by fwrite as $str= 'dynamic text from each run'; $myFile = "testFile.txt"; $fh = fopen($myFile, 'a') or die("can't open file"); $stringData = "$str\n"; fwrite($fh, $stringData); fclose($fh); but I want to avoid duplicate to keep the file small. I want to avoid writing if the term is already saved in the file. I want to have a file containing unique lines. Quote Link to comment https://forums.phpfreaks.com/topic/237551-write-file-unique-append/ Share on other sites More sharing options...
Fadion Posted May 27, 2011 Share Posted May 27, 2011 Member AbraCadaver gave a good solution in this thread that will work in your case too. <?php $str = 'some dynamic text'; $file = 'testFile.txt'; $lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); if (!in_array($str, $lines)) { $h = fopen($file, 'a'); fwrite($h, $str . "\n"); fclose($h); echo 'Line written successfully.'; } else { echo 'Line already exists.'; } ?> Quote Link to comment https://forums.phpfreaks.com/topic/237551-write-file-unique-append/#findComment-1221008 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.