Jump to content

write file - unique append


etrader

Recommended Posts

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

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.';
}
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.