Hướng dẫn php read last 10 lines of file - php đọc 10 dòng cuối cùng của tệp

35

Mới! Lưu câu hỏi hoặc câu trả lời và sắp xếp nội dung yêu thích của bạn. Tìm hiểu thêm.
Learn more.

Tôi có một tệp có tên

$lines=array[];
$fp = fopen["file.txt", "r"];
while[!feof[$fp]]
{
   $line = fgets[$fp, 4096];
   array_push[$lines, $line];
   if [count[$lines]>5]
       array_shift[$lines];
}
fclose[$fp];
3 là cập nhật bằng cách thêm các dòng vào nó.

Tôi đang đọc nó bằng mã này:

$fp = fopen["file.txt", "r"];
$data = "";
while[!feof[$fp]]
{
$data .= fgets[$fp, 4096];
}
echo $data;

và một số lượng lớn các dòng xuất hiện. Tôi chỉ muốn lặp lại 5 dòng cuối cùng của tệp

Làm thế nào tôi có thể làm điều đó ?

$lines=array[];
$fp = fopen["file.txt", "r"];
while[!feof[$fp]]
{
   $line = fgets[$fp, 4096];
   array_push[$lines, $line];
   if [count[$lines]>5]
       array_shift[$lines];
}
fclose[$fp];
3 là như thế này:

11111111111111


33333333333333
44444444444

55555555555555
66666666666

Đã hỏi ngày 2 tháng 6 năm 2010 lúc 21:09Jun 2, 2010 at 21:09

2

Đối với một tệp lớn, đọc tất cả các dòng vào một mảng với tệp [] là một chút lãng phí. Đây là cách bạn có thể đọc tệp và duy trì bộ đệm của 5 dòng cuối cùng:

$lines=array[];
$fp = fopen["file.txt", "r"];
while[!feof[$fp]]
{
   $line = fgets[$fp, 4096];
   array_push[$lines, $line];
   if [count[$lines]>5]
       array_shift[$lines];
}
fclose[$fp];

Bạn có thể tối ưu hóa điều này thêm một chút với một số heuristic về độ dài dòng có khả năng bằng cách tìm kiếm một vị trí, giả sử, khoảng 10 dòng từ cuối và quay trở lại nếu điều đó không mang lại 5 dòng. Đây là một triển khai đơn giản chứng minh rằng:

//how many lines?
$linecount=5;

//what's a typical line length?
$length=40;

//which file?
$file="test.txt";

//we double the offset factor on each iteration
//if our first guess at the file offset doesn't
//yield $linecount lines
$offset_factor=1;


$bytes=filesize[$file];

$fp = fopen[$file, "r"] or die["Can't open $file"];


$complete=false;
while [!$complete]
{
    //seek to a position close to end of file
    $offset = $linecount * $length * $offset_factor;
    fseek[$fp, -$offset, SEEK_END];


    //we might seek mid-line, so read partial line
    //if our offset means we're reading the whole file, 
    //we don't skip...
    if [$offset$linecount]
        {
            array_shift[$lines];
            $complete=true;
        }
    }

    //if we read the whole file, we're done, even if we
    //don't have enough lines
    if [$offset>=$bytes]
        $complete=true;
    else
        $offset_factor*=2; //otherwise let's seek even further back

}
fclose[$fp];

var_dump[$lines];

Đã trả lời ngày 2 tháng 6 năm 2010 lúc 21:21Jun 2, 2010 at 21:21

Paul Dixonpaul DixonPaul Dixon

291K51 Huy hiệu vàng310 Huy hiệu bạc344 Huy hiệu đồng51 gold badges310 silver badges344 bronze badges

1

Mã chưa được kiểm tra, nhưng nên hoạt động:

$file = file["filename.txt"];
for [$i = max[0, count[$file]-6]; $i < count[$file]; $i++] {
  echo $file[$i] . "\n";
}

Gọi

$lines=array[];
$fp = fopen["file.txt", "r"];
while[!feof[$fp]]
{
   $line = fgets[$fp, 4096];
   array_push[$lines, $line];
   if [count[$lines]>5]
       array_shift[$lines];
}
fclose[$fp];
5 sẽ xử lý tệp nhỏ hơn 6 dòng.

Đã trả lời ngày 2 tháng 6 năm 2010 lúc 21:16Jun 2, 2010 at 21:16

MaerlynmaerlynMaerlyn

33.3K17 Huy hiệu vàng94 Huy hiệu bạc84 Huy hiệu đồng17 gold badges94 silver badges84 bronze badges

4

Nếu bạn đang ở trên một hệ thống Linux, bạn có thể làm điều này:

$lines = `tail -5 /path/to/file.txt`;

Đã trả lời ngày 2 tháng 6 năm 2010 lúc 21:27Jun 2, 2010 at 21:27

RobrobRob

7.9423 Huy hiệu vàng33 Huy hiệu bạc37 Huy hiệu đồng3 gold badges33 silver badges37 bronze badges

1

Mở các tệp lớn bằng

$lines=array[];
$fp = fopen["file.txt", "r"];
while[!feof[$fp]]
{
   $line = fgets[$fp, 4096];
   array_push[$lines, $line];
   if [count[$lines]>5]
       array_shift[$lines];
}
fclose[$fp];
6 có thể tạo ra một mảng lớn, bảo lưu một đoạn bộ nhớ đáng kể.

Bạn có thể giảm chi phí bộ nhớ với

$lines=array[];
$fp = fopen["file.txt", "r"];
while[!feof[$fp]]
{
   $line = fgets[$fp, 4096];
   array_push[$lines, $line];
   if [count[$lines]>5]
       array_shift[$lines];
}
fclose[$fp];
7 vì nó lặp lại thông qua từng dòng.

Sử dụng phương pháp

$lines=array[];
$fp = fopen["file.txt", "r"];
while[!feof[$fp]]
{
   $line = fgets[$fp, 4096];
   array_push[$lines, $line];
   if [count[$lines]>5]
       array_shift[$lines];
}
fclose[$fp];
8 [của
$lines=array[];
$fp = fopen["file.txt", "r"];
while[!feof[$fp]]
{
   $line = fgets[$fp, 4096];
   array_push[$lines, $line];
   if [count[$lines]>5]
       array_shift[$lines];
}
fclose[$fp];
9] để tìm nạp dòng cuối cùng. Sau đó, bạn nên trừ đi giá trị khóa hiện tại 5.

Để có được dòng cuối cùng, sử dụng

//how many lines?
$linecount=5;

//what's a typical line length?
$length=40;

//which file?
$file="test.txt";

//we double the offset factor on each iteration
//if our first guess at the file offset doesn't
//yield $linecount lines
$offset_factor=1;


$bytes=filesize[$file];

$fp = fopen[$file, "r"] or die["Can't open $file"];


$complete=false;
while [!$complete]
{
    //seek to a position close to end of file
    $offset = $linecount * $length * $offset_factor;
    fseek[$fp, -$offset, SEEK_END];


    //we might seek mid-line, so read partial line
    //if our offset means we're reading the whole file, 
    //we don't skip...
    if [$offset$linecount]
        {
            array_shift[$lines];
            $complete=true;
        }
    }

    //if we read the whole file, we're done, even if we
    //don't have enough lines
    if [$offset>=$bytes]
        $complete=true;
    else
        $offset_factor*=2; //otherwise let's seek even further back

}
fclose[$fp];

var_dump[$lines];
0. [Vâng, đây là một cách giải quyết.]

$file = new SplFileObject['large_file.txt', 'r'];

$file->seek[PHP_INT_MAX];

$last_line = $file->key[];

$lines = new LimitIterator[$file, $last_line - 5, $last_line];

print_r[iterator_to_array[$lines]];

Onosendai

3.9402 Huy hiệu vàng24 Huy hiệu bạc46 Huy hiệu đồng2 gold badges24 silver badges46 bronze badges

Đã trả lời ngày 24 tháng 1 năm 2016 lúc 20:58Jan 24, 2016 at 20:58

Wallace Maxterswallace MaxtersWallace Maxters

3.2112 Huy hiệu vàng26 Huy hiệu bạc28 Huy hiệu đồng2 gold badges26 silver badges28 bronze badges

2

function ReadFromEndByLine[$filename,$lines]
{

        /* freely customisable number of lines read per time*/
        $bufferlength = 5000;

        $handle = @fopen[$filename, "r"];
        if [!$handle] {
                echo "Error: can't find or open $filename
\n"; return -1; } /*get the file size with a trick*/ fseek[$handle, 0, SEEK_END]; $filesize = ftell[$handle]; /*don't want to get past the start-of-file*/ $position= - min[$bufferlength,$filesize]; while [$lines > 0] { if [$err=fseek[$handle,$position,SEEK_END]] { /* should not happen but it's better if we check it*/ echo "Error $err: something went wrong
\n"; fclose[$handle]; return $lines; } /* big read*/ $buffer = fread[$handle,$bufferlength]; /* small split*/ $tmp = explode["\n",$buffer]; /*previous read could have stored a partial line in $aliq*/ if [$aliq != ""] { /*concatenate current last line with the piece left from the previous read*/ $tmp[count[$tmp]-1].=$aliq; } /*drop first line because it may not be complete*/ $aliq = array_shift[$tmp]; $read = count[$tmp]; if [ $read >= $lines ] { /*have read too much!*/ $tmp2 = array_slice[$tmp,$read-$n]; /* merge it with the array which will be returned by the function*/ $lines = array_merge[$tmp2,$lines]; /* break the cycle*/ $lines = 0; } elseif [-$position >= $filesize] { /* haven't read enough but arrived at the start of file*/ //get back $aliq which contains the very first line of the file $lines = array_merge[$aliq,$tmp,$lines]; //force it to stop reading $lines = 0; } else { /*continue reading...*/ //add the freshly grabbed lines on top of the others $lines = array_merge[$tmp,$lines]; $lines -= $read; //next time we want to read another block $position -= $bufferlength; //don't want to get past the start of file $position = max[$position, -$filesize]; } } fclose[$handle]; return $lines; }

Điều này sẽ nhanh chóng cho các tệp lớn hơn nhưng rất nhiều mã cho một nhiệm vụ đơn giản, nếu có các tệp lớn, hãy sử dụng điều này

ReadFromEndByLine['myFile.txt',6];

Đã trả lời ngày 2 tháng 6 năm 2010 lúc 21:19Jun 2, 2010 at 21:19

RobertpittrobertpittRobertPitt

56.3K21 Huy hiệu vàng113 Huy hiệu bạc159 Huy hiệu đồng21 gold badges113 silver badges159 bronze badges

3

Đây là một câu hỏi phỏng vấn phổ biến. Đây là những gì tôi đã viết năm ngoái khi tôi được hỏi câu hỏi này. Hãy nhớ rằng mã bạn nhận được trên Stack Overflow được cấp phép với Creative Commons Share-giống nhau với sự phân bổ cần thiết.

Chủ Đề