【问题标题】:get the first 3 lines of a text file in php [duplicate]在php中获取文本文件的前3行[重复]
【发布时间】:2015-03-23 03:59:46
【问题描述】:

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

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

【问题讨论】:

  • 使用file() 并获取索引0-2
  • 你可以从那里得到想法stackoverflow.com/questions/13246597/…如果你用谷歌搜索,你会得到更多帮助。
  • 怎么样?你能给我正确的代码吗?我想这不是很困难,但我不擅长用PHP打开/编辑/读取文件
  • 这里可能有一百个问题与此极为相似。您是否尝试过搜索该网站?
  • 文件有多大?如果它很大,那么您应该避免使用file()。它将整个文件读入内存。仅仅获得 3 行就有点过头了。

标签: php text lines


【解决方案1】:

更简单:

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

【讨论】:

  • 这会将整个文件读入数组元素,然后隔离前三个元素。简洁吗?是的。是否精益/高效?没有。
【解决方案2】:

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

// 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】:

    file() 函数将文件的行作为数组返回。除非文件很大(数兆字节),否则您可以使用 array_slice 获取前 3 个元素:

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

    【讨论】:

    • 这会将整个文件读入数组元素,然后隔离前三个元素。简洁吗?是的。是否精益/高效?没有。
    • @mickmackusa 取决于文件有多大。如果你想要一个 100 行文件的前 3 行,这很好。如果是兆字节,还有更好的方法。
    • “这会将整个文件读入数组元素,然后隔离前三个元素。” 是事实。是否值得担心这种技术的开销?这取决于,是的。我只是让研究人员意识到可能会选择“较短的复制面”,这可能不适合他们的项目。
    • Premature optimization is the root of all evil。做任何你认为最自然和可读的事情,如果它成为性能瓶颈,则对其进行优化。 @mickmackusa
    • 我在答案中添加了限定符
    猜你喜欢
    • 1970-01-01
    • 2012-07-20
    • 2014-12-07
    • 1970-01-01
    • 1970-01-01
    • 2015-12-12
    • 1970-01-01
    • 2019-02-26
    • 1970-01-01
    相关资源
    最近更新 更多