Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

how to remove every line except the first 20 using php from a text file?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
710 views
Welcome To Ask or Share your Answers For Others

1 Answer

If loading the entire file in memory is feasible you can do:

// read the file in an array.
$file = file($filename);

// slice first 20 elements.
$file = array_slice($file,0,20);

// write back to file after joining.
file_put_contents($filename,implode("",$file));

A better solution would be to use the function ftruncate which takes the file handle and the new size of the file in bytes as follows:

// open the file in read-write mode.
$handle = fopen($filename, 'r+');
if(!$handle) {
    // die here.
}

// new length of the file.
$length = 0;

// line count.
$count = 0;

// read line by line.    
while (($buffer = fgets($handle)) !== false) {

        // increment line count.
        ++$count;

        // if count exceeds limit..break.
        if($count > 20) {
                break;
        }

        // add the current line length to final length.
        $length += strlen($buffer);
}

// truncate the file to new file length.
ftruncate($handle, $length);

// close the file.
fclose($handle);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...