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. 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.'; } ?> Link to comment https://forums.phpfreaks.com/topic/237551-write-file-unique-append/#findComment-1221008 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.