简体   繁体   中英

How do i read first 5 lines in php?

I am trying to read the first 5 line code-block in txt file, please how do i do this

I have this php code to get only the first line

<?php
$file = 'example.txt';
$f = fopen($file, 'r');
$line = fgets($f);
    while (($line = fgets( $f)) !== false) {
            for ($list = 1; $list < 6; $list++){
                $codeline= htmlentities($line );
            }
        }   
fclose($f); 
?>

You can use a for loop:

for ($x = 1; $x < 6; $x++) {
    $line = fgets($f);
}

Even more simple:

<?php
$file_data = array_slice(file('file.txt'), 0, 5);
print_r($file_data);

source: get the first 3 lines of a text file in php from @paul-denisevich

To open and read a file line by line:

$file = fopen( "/path/to/file.txt", "r" );

$index=0;
while ((( $line = fgets( $file )) !== false) && ( $index++ < 5 )) {

    echo $line;
}

fclose( $file );

Here, I am initializing a variable index to 0 .

In the while loop, we will use fgets to read the next line of the file, and assign it to the variable line . We will also check that the value of index is less then 5, our desired line count, in addition to incrementing the value of the index, after we have read the line.

Once the value of index has reached > 5, the loop will exit, and the file stream will be closed.

The advantage of using fopen and fgets over something like file , is that the latter will load the entire contents of the file into memory - even if you do not plan on using the whole thing.

With a multi line file , the above code will print out the first five lines.

This is a multi line

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM