This question already has an answer here:
- How to read a large file line by line? 13 answers
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?
<?php
$file = file_get_contents("text.txt");
//echo the first 3 lines, but it's wrong
echo $file;
?>
The
file()
function returns the lines of a file as an array. You can then usearray_slice
to get the first 3 elements of this:Even more simple:
Open the file, read lines, close the file: