The text file (from which my function grab info) is being recreated everyday at 00:00 and my application starts slowly during the day to add lines by lines as log file. The file is approximately 1 mb and with around 6,000 lines at the end of the day. So, it's not really small file. The function is grabbing latest 21 lines from the text file to display latest 21 death/kills for a game and the script can be accessed by a lot of users to check the log statistics.
My question is how I can make the script with better performance because file()
is reading the whole file actually lines by lines, so what's a better way to do this? Can it affect the performance if a lot of people access the log page to display this info from the text file or for 6,000 lines, it should be all good ?
The file is as plain text in .txt format and these are an example lines from the file:
1,42,16, 201,stackoverflow_user, 1, 6762160, 39799, 9817242, 6762160, 39884, 10010545,stackoverflow_user, 2, 1351147, 1165, 483259, 1351147, 1115, 241630, 0
1,46,27, 201,[stackoverflow_user | stackoverflow_userother], 1, 4078465, 286991, 1594830, 4078465, 287036, 1643156,stackoverflow_user, 2, 1357147, 1115, 241630, 1357147, 1065, 120815, 0
My function:
# read a file into an array
$lines = file('C:/path/to/file.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
# flip our array over so the last lines of the file are first.
$lines = array_reverse($lines);
$n = 1;
$wanted = 21; # or however many lines you want.
$content = '';
foreach ($lines as $l) {
# treat the data as comma-separated values
$arr = explode(",", $l);
# if col 5 has multiple values, take the first one
if (preg_match("/\[(.+?) \|/", $arr[4], $matches)) {
$arr[4] = $matches[1];
}
# is arr[4] the same as arr[12]?
if ($arr[4] !== $arr[12]) {
# these two are not equal, so use these values
$data = array('rank-pos' => $n++, 'rank-name' => $arr[4], 'rank-dmuser' => $arr[12]);
$content .= Template::Load('rankinguserdm-' . ($n % 2 == 1 ? 2 : 1), $data);
}
# have we got enough data?
if ($n === $wanted) {
break;
}
}
$this->content = Template::Load('user_rankingsdm', array('rankings' => $content));
}