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

时间:2015-01-24 01:28:57

标签: php text lines

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

<?php
$file = file_get_contents("text.txt");
//echo the first 3 lines, but it's wrong
echo $file;
?>

3 个答案:

答案 0 :(得分:8)

更简单:

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

答案 1 :(得分:4)

打开文件,读取行,关闭文件:

// 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);
}

答案 2 :(得分:3)

file()函数将文件的行作为数组返回。然后,您可以使用array_slice获取前3个元素:

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