user4491831
user4491831

Reputation: 11

Code is only saving the last entry of the loop

I want to filter one text file by writing the results to a second text file.

I have a little bit of code and it doesn't work like it should work, it is only writing the LAST line of the first text file into a separate backup text file.

Code:

//filter the ingame bans
$search = "permanently"; 
$logfile = "ban_list.txt";
$timestamp = time();

// Read from file 
$file = fopen($logfile, "r");
while( ($line =  fgets($file) )!= false)
{
    if(stristr($line,$search))
    {
        $cache_ig = "ingamebanlist.txt";
        $fh = fopen($cache_ig, 'w') or die("can't open file");
        $content = "\n";
        fwrite($fh, $content);
        $content = $line;
        fwrite($fh, $content);
        fclose($fh);    
    }
}

I personally do not see any errors in my code, please help.

REMEMBER: It does kind of work, but it only writes the LAST line of the ban_list.txt file into the ingamebanlist.txt file...

Upvotes: 0

Views: 90

Answers (1)

Prix
Prix

Reputation: 19528

What happens with your code is that you open(using write mode), write and close inside your loop so it will only ever write 1 entry then overwrite it until the last entry, thus only saving the last item.

What you want is to have it outside the loop like this:

<?php
$search = "permanently"; 
$logfile = "ban_list.txt";
$cache_ig = "ingamebanlist.txt";
$timestamp = time();

$read = fopen($logfile, "r") or die("can't read file");
$write = fopen($cache_ig, 'w') or die("can't write to file");
while(($line = fgets($read)) !== false)
{
    if(stristr($line,$search))
    {
        fwrite($write, $line . "\n");
    }
}
fclose($write);
fclose($read);

An alternative solution would be to use a instead of w at your fopen since w will:

Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

While a will:

Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.

Which would allow your code to work as is without any changes but the line:

$fh = fopen($cache_ig, 'w') or die("can't open file");

To:

$fh = fopen($cache_ig, 'a') or die("can't open file");

Upvotes: 1

Related Questions