用php读取文件行(fgets) [英] Read file lines backwards (fgets) with php
问题描述
$ fh = fopen我有一个txt文件,我想向后读取,目前我正在使用这个: ( 'myfile.txt的', 'R');
while($ line = fgets($ fh)){
echo $ line。< br />;
输出文件中的所有行。
我想从底部到顶部读取这些行。
有没有办法做到这一点? >第一种方法:
$ file = file(test.txt);
$ file = array_reverse($ file);
foreach($ file as $ f){
echo $ f。< br />;
第二种方法(a):
要完全反转文件:
$ fl = fopen(\some_file。 txt,r);
for($ x_pos = 0,$ output =''; fseek($ fl,$ x_pos,SEEK_END)!== -1; $ x_pos--){
$ output。= fgetc($ FL);
}
fclose($ fl);
print_r($ output);
第二种方式(b):
当然, ...
$ fl = fopen(\some_file.txt,r) ;
for $($ x_pos = 0,$ ln = 0,$ output = array(); fseek($ fl,$ x_pos,SEEK_END)!== -1; $ x_pos--){
$ char = fgetc($ fl);
if($ char ===\\\
){
//分析完成的行$ output [$ ln]如果需要的话
$ ln ++;
继续;
}
$输出[$ ln] = $ char。 ((array_key_exists($ ln,$ output))?$ output [$ ln]:'');
}
fclose($ fl);
print_r($ output);
I have a txt file that I want to read backwards, currently I'm using this:
$fh = fopen('myfile.txt','r');
while ($line = fgets($fh)) {
echo $line."<br />";
}
This outputs all the lines in my file.
I want to read the lines from bottom to top.
Is there a way to do it?
First way:
$file = file("test.txt");
$file = array_reverse($file);
foreach($file as $f){
echo $f."<br />";
}
Second Way (a):
To completely reverse a file:
$fl = fopen("\some_file.txt", "r"); for($x_pos = 0, $output = ''; fseek($fl, $x_pos, SEEK_END) !== -1; $x_pos--) { $output .= fgetc($fl); } fclose($fl); print_r($output);
Second Way (b): Of course, you wanted line-by-line reversal...
$fl = fopen("\some_file.txt", "r"); for($x_pos = 0, $ln = 0, $output = array(); fseek($fl, $x_pos, SEEK_END) !== -1; $x_pos--) { $char = fgetc($fl); if ($char === "\n") { // analyse completed line $output[$ln] if need be $ln++; continue; } $output[$ln] = $char . ((array_key_exists($ln, $output)) ? $output[$ln] : ''); } fclose($fl); print_r($output);
这篇关于用php读取文件行(fgets)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!