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

Link to comment
Share on other sites

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.