Trying to write content to a file I've created, it reads all 3 lines, but when I change the lines to read 2 it still prints out 3?

Issue

$my_content = "This is the first line\n
    This is the second line\n
    This is the third line\n";
    
$my_filename = "save.txt";  

 function file_writer(string $file_to_write, string $content_to_write){
    $file = fopen($file_to_write, "w") or die("Unable to open file");
    file_put_contents($file_to_write, $content_to_write);
    fclose($file);
}
file_writer($my_filename, $my_content);

function file_reader(string $file_to_read, int $num_lines) {
    $file = fopen($file_to_read, "r");
    while(! feof($file))  
    {
        $line = fgets($file);
        echo $line;
    }
}
**file_reader($my_filename, 3);**

Solution

Try this:

function file_reader(string $file_to_read, int $num_lines) {
$file = fopen($file_to_read, "r");
$c = 0;
while(! feof($file) && $c != $num_lines)  
{
    $c = $c+1;
    $line = fgets($file);
    echo $line;
    }
}

Your other problem is that you have newlines after newlines.

$my_content = "This is the first line\nThis is the second line\nThis is the third line\n";

Answered By – greatusername

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published