ChrisRockGM
ChrisRockGM

Reputation: 438

How do I count the lines of a text file and delete the first one?

I have an html file that I use for my chat log. I am rather new to PHP I/O and I managed to make this (which works, but it isn't very helpful).

while(!feof($fp)){
    $line = fgets($fp);
    $lines++;
}

It counts the amount of lines in a file. I want to count the amount of lines and say that if there are more than 15 lines, then delete the first line so that there are never more than 15 lines.

Upvotes: 1

Views: 107

Answers (2)

Adrian Romero
Adrian Romero

Reputation: 577

Simple html php is a usefull library for manage DOM in html files, use like for delete elements:

$html = file_get_html('test.htm');

$e = $html->find("#div1", 0);

$e->outertext = '';

$html->save('test.htm');

Upvotes: -1

AbraCadaver
AbraCadaver

Reputation: 78994

I like this:

$lines   = file('/path/to/file.html');
$last_15 = array_slice($lines, -15, 15);
file_put_contents('/path/to/file.html', $last_15);

Or one-liner:

file_put_contents('/path/to/file.html', array_slice(file('/path/to/file.html'), -15, 15));

Upvotes: 3

Related Questions