get the first 3 lines of a text file in php [duplicate]

只愿长相守 提交于 2019-12-04 21:31:36

Even more simple:

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

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

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);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!