Php read first 10 lines file

I am developing a website in PHP, and I must include in the index the first 3 lines of a text file in PHP. How can I do that?


asked Jan 24, 2015 at 1:28

5

Even more simple:

answered Jan 24, 2015 at 1:39

2

Open the file, read lines, close the file:

// Open the file for reading
$file = 'file.txt';
$fh = fopen($file, 'rb');

// Handle failure
if ($fh === false) {
    die('Could not open file: '.$file);
}
// Loop 3 times
for ($i = 0; $i < 3; $i++) {
    // Read a line
    $line = fgets($fh);

    // If a line was read then output it, otherwise
    // show an error
    if ($line !== false) {
        echo $line;
    } else {
        die('An error occurred while reading from file: '.$file);
    }
}
// Close the file handle; when you are done using a
// resource you should always close it immediately
if (fclose($fh) === false) {
    die('Could not close file: '.$file);
}

answered Jan 24, 2015 at 1:36

Sverri M. OlsenSverri M. Olsen

12.8k3 gold badges35 silver badges51 bronze badges

The file() function returns the lines of a file as an array. Unless the file is huge (multiple megabytes), you can then use array_slice to get the first 3 elements of this:

$lines = file('file.txt');
$first3 = array_slice($lines, 0, 3);
echo implode('', $first3);

answered Jan 24, 2015 at 1:39

BarmarBarmar

696k53 gold badges469 silver badges578 bronze badges

7

It's nice to be able to generate an html table from a PHP array. I know how to
do this, but the array in question is built from a file. The file in question
can be very long, and I only want the first 10 lines. So, I'd like to reduce
the overhead it takes to read the file into the array by limiting the number of
lines read in - rather than have the entire file read in and then limiting the
output to the html table.

$visits= file("visdata.txt");
//reverse the array so table is ordered by date decending
$visits = array_reverse ($visits);
//show only the last 10 visitors
$number_of_visits = count($visits);
if ($number_of_visits > 10)
{
$number_of_visits = 10;
}
echo
"

";
....
....
....
....

There must be a way to limit how many lines from the file are read into the
array -- any suggestions?

Thanks in advance.

Jul 17 '05 #1

Introduction

Here you will see how to read last n lines from a file in PHP, where n could be replaced by any positive integer number, such as, 1, 2, 5, 10 etc. Generally most of the times you may use to read the file in forward direction, i.e., from the beginning of the file and apply some business processing logic on file data according to the application’s requirements.

Sometimes you need to read a file in backward direction, i.e., from the end of the file and you may need to extract last few lines from a file for your application’s need. Then you can use one of the solutions from below code snippets.

I am going to use text file in this example. The sample file can be downloaded later from the source code link given at the bottom of this tutorial.

Related Posts:

  • How to read last n lines from a file using Java
  • How to read last n line from a file using Python

Prerequisites

Apache HTTP Server 2.4 (Optional), PHP 7.4.3 – 7.4.27

Project Directory

It’s assumed that you have setup Apache and PHP in Windows system.

Now I will create a project root directory called php-file-read-last-n-lines under the Apache server’s htdocs folder or if you are not using HTTP Apache server then you can create the project folder anywhere in the physical drive.

I may not mention the project root directory in subsequent sections and I will assume that I am talking with respect to the project root directory.

Read Last n Lines

Your file may be a small, medium or big depending on your project’s requirements and here I will present with two different solutions you can use according to your need.

Solution – One

When you need to extract last few lines from a small file then you can use below solution.

The sample file license.txt is available in the source code link.

 0) {
		for ($i = $readLines; $i < count($file); $i++) {
			echo $file[$i];
			echo nl2br("\n");
		}
	} else {
		echo 'file does not have required no. of lines to read';
	}

?>

The above solution will consume much memory, so if your file is small then only use the above solution.

Executing the above code will give you the following output assuming n=10:

Php read first 10 lines file

Solution – Two

This solution will work for your small as well as very big file. I will use here SplFileObject to reduce the memory cost. Use the seek() method to fetch the last line. You should then subtract the current key value by n, where n being the non-zero positive integer.

seek(PHP_INT_MAX);
	$last_line = $file->key();
	$lines = new LimitIterator($file, $last_line - n, $last_line); //n being non-zero positive integer
	print_r(iterator_to_array($lines));
	
	// Iterate each element
	/*$it = iterator_to_array($lines);
	
	foreach($it as $ele){
		echo nl2br($ele . "\n");
	}*/
?>

Executing the above code will give you the following output assuming n=10:

Php read first 10 lines file

Note that SplFileObject class has a private property that holds the file pointer. Therefore, there is no method to close the file handle, and you get into situations where you are not able to delete the file with unlink() method, because an SplFileObject still has a handle open. Then you have to do some workaround in the following way to delete the file.

$file = new SplFileObject("filename.txt");
$file = null; //explicitly assign null
unlink($file); //now delete the file

That’s all. Hope you got idea how to read last n lines from a file in PHP.

Source Code

Download

How do I make the first line of a file read only in PHP?

PHP Read Single Line - fgets() The fgets() function is used to read a single line from a file.

How to get lines of a file in PHP?

$filePath = "test. txt" ; $lines = count (file( $filePath ));

How do I read the last line of a text file in PHP?

$line; fseek($f, $cursor--, SEEK_END); $char = fgetc($f); } echo $line; Output will be the last line of the text file will be read and displayed.

How do you get the first line of a string in PHP?

$line = preg_split('#\r?\ n#', ltrim($input), 2)[0]; for the first non-empty string.