在php中获取文本文件的前3行

在php中获取文本文件的前3行,php,text,lines,Php,Text,Lines,我正在用PHP开发一个网站,我必须在索引中包含PHP文本文件的前3行。我该怎么做 <?php $file = file_get_contents("text.txt"); //echo the first 3 lines, but it's wrong echo $file; ?> 打开文件,读取行,关闭文件: // Open the file for reading $file = 'file.txt'; $fh = fopen($file, 'rb'); // Handle

我正在用PHP开发一个网站,我必须在索引中包含PHP文本文件的前3行。我该怎么做

<?php
$file = file_get_contents("text.txt");
//echo the first 3 lines, but it's wrong
echo $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);
}
file函数将文件的行作为数组返回。除非文件是巨大的多兆字节,否则您可以使用array_slice获取此文件的前3个元素:

$lines = file('file.txt');
$first3 = array_slice($lines, 0, 3);
echo implode('', $first3);
更简单的是:

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

使用文件并获取索引0-2你可以从那里得到想法,如果你用谷歌搜索它,你会得到更多帮助。如何?你能给我正确的密码吗?我想这不是很难,但我不擅长在php中打开/编辑/阅读文件这里可能有100个问题与此非常相似。你试过搜索网站吗?文件有多大?如果它很大,那么您可能应该避免使用文件。它将把整个文件读入内存。仅仅得到3行就有点过分了。这会将整个文件读入数组元素,然后分离前三个元素。它简洁吗?对它是否精干/高效?否。这会将整个文件读入数组元素,然后分离前三个元素。它简洁吗?对它是否精干/高效?不。@mickmackusa取决于文件的大小。如果您想要100行文件的前3行,这很好。如果是兆字节,有更好的方法。它将整个文件读入数组元素,然后分离前三个元素。这是事实。值得担心这种技术的开销吗?那要看情况,是的。我只是想让研究人员意识到,他们可能会选择较短的意大利面,而这可能不适合他们的项目。。做您认为最自然、最可读的事情,如果它成为性能瓶颈,请对其进行优化@我在答案中加了一个限定词