[英]How to start reading txt file from a specified line using PHP?
我有一個包含更改日志的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;
該嵌套循環不會降低性能,從某種意義上來說,它並不是嵌套循環,而是在多個變量上組合增長的循環。 雖然沒有必要那樣寫。 這是避免它的另一種方法。 試試這個(這里是偽代碼):
// skim through the beginning of the file, break upon finding the start
// of the portion I care about.
while (!feof($file)) {
if $line matches beginning marker, break;
}
// now read and process until the endmarker (or eof...)
while (!feof($file)) {
if $line matches endmarker, break;
filter/process/store line here.
}
另外,絕對沒有必要進行雙重檢查。 為什么在那里?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.