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

一曲冷凌霜 提交于 2019-12-22 01:21:37

问题


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

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