我有一个包含更改日志的 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/