问题
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;
?>
回答1:
Even more simple:
<?php
$file_data = array_slice(file('file.txt'), 0, 3);
print_r($file_data);
回答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);
}
回答3:
The file()
function returns the lines of a file as an array. 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);
来源:https://stackoverflow.com/questions/28121329/get-the-first-3-lines-of-a-text-file-in-php