php - 如何使用PHP从指定行开始读取txt文件?

标签 php performance

我有一个包含更改日志的 txt 文件。我正在尝试仅显示当前版本的新更改。

我编写了一个函数来读取文件并检查每一行是否有想要的单词,如果找到这些单词,它就会开始获取内容并将其推送到数组中。

我搜索了一下是否有示例,但每个人都在谈论如何在指定行停止,而不是从某一行开始。

这是我使用的代码:

public function load($theFile, $beginPosition, $doubleCheck) {

    // Open file (read-only)
    $file = fopen($_SERVER['DOCUMENT_ROOT'] . '/home/' . $theFile, 'r');

    // Exit the function if the the file can't be opened
    if (!$file) {
        return;
    }

    $changes = Array();

    // While not at the End Of File
    while (!feof($file)) {

        // Read current line only
        $line = fgets($file);

        // This will check if the current line has the word we look for to start loading
        $findBeginning = strpos($line, $beginPosition);

        // Double check for the beginning
        $beginningCheck = strpos($line, $doubleCheck);

        // Once you find the beginning
        if ($findBeginning !== false && $beginningCheck !== false) {

            // Start storing the data to an array
            while (!feof($file)) {

                $line = fgets($file);

                // Remove space and the first 2 charecters ('-' + one space)
                $line = trim(substr($line, 2));

                if (!empty($line)) { // Don't add empty lines
                    array_push($changes, $line);
                }
            }
        }
    }

    // Close the file to save resourses
    fclose($file);

    return $changes;
}

它目前正在工作,但正如您所看到的,它是嵌套循环,这不好,并且如果 txt 文件增长,将需要更多时间!

我正在尝试提高性能,那么有没有更好的方法来做到这一点?

最佳答案

比你想象的简单得多

 $found = false;
 $changes = array();
 foreach(file($fileName) as $line)
    if($found)
       $changes[] = $line;
    else
       $found = strpos($line, $whatever) !== false;

关于php - 如何使用PHP从指定行开始读取txt文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3462912/

相关文章:

python - 适合实时设置的 Redis 管道?

java - Switch 似乎比 if 慢

python - NumPy:按选定的第二轴元素对 ndarray 第一轴进行排序

php - 如何通过前缀分隔php数组项

javascript - 中间变量——性能成本是多少?

php - 如何用php从json数组中提取数据?

PHP 从用户输入中删除 html 和 php 代码

java - SQL 缩放 : should I try to minimize queries when having multiple OR column conditions?

php - Mysql、PHPmyadmin 和 Apache 的 Docker 错误

php - 哪些代码应该放在 MVC 结构中的什么地方