Thursday 30 August 2018

delete a new line from the txt file after inserting the value

I create a txt file from a folder in that way:

$fp = fopen("mylist.txt","rw+");
foreach(glob("folder/*.*") as $value){
fwrite($fp,$value."\n");
}

and it create inside the txt each items, one per line, BUT it also add a newline at the end of the file.
This is the content of mylist.txt:
foldelr/file1.mp3
folder/file2.mp3
(BLANK NEWLINE)

I tried to remove the blank newline at the end of the txt file, in this way:
$filetxt = fopen("mylist.txt","r");
$rtrim = rtrim($filetxt, "\n");
$newfile = file_put_contents("newfile.txt", $rtrim);

But it doesn't work, because in the "newfile.txt", i still have the newline blank after last file name.
I tried to convert file in array, use "array_diff()" to remove the last line, but it fail. I tried also all the suggestions in this thread: remove new line characters from txt file using php but not fix my problem.
Does anyone can please help me to understand what i'm missing or mistaken?
Kind Regards
Brus

Use file_get_contents method it works fine for me
    $fp = fopen("mylist.txt","rw+");
    foreach (glob("test/*.*") as $value) {
        fwrite($fp, $value . "\n");
    }

    $filetxt = file_get_contents("mylist.txt");
    $rtrim =  rtrim($filetxt, "\n");
    $newfile = file_put_contents("mylist.txt", $rtrim);

Or You can also remove the last newline by using the array count.
$fp = fopen("mylist.txt","rw+");
$i =0;
foreach(glob("folder/*.*") as $value){
  $i++;
  if($i < count(glob("folder/*.*")))
    fwrite($fp,$value."\n");
  else
    fwrite($fp,$value);
}

0 comments:

Post a Comment