PHP fseek function Read large file two ways _php instance

Source: Internet
Author: User

PHP read large files, using the Fseek function is the most common way, it does not need to read all the contents of the file into memory, but directly through the pointer to operate, so the efficiency is quite efficient. There are several different ways to manipulate a file using fseek, and there may be a slight difference in efficiency, Here are two common methods.

Method One:

First through the fseek find the last EOF of the file, then find the starting position of the last line, take this row of data, find the first line of the starting position, and then take the position of the line, and so on until the $num line is found. The implementation code is as follows:

Complete code Execution time consuming 0.0095 (s)

function tail ($fp, $n, $base =5)
{
  assert ($n >0);
  $pos = $n +1;
  $lines = Array ();
  while (count ($lines) < = $n) {
    try{
      fseek ($fp,-$pos, seek_end);
    } catch (Exception $e) {
      fseek (0);
      break;
    $pos *= $base;
    while (!feof ($fp)) {
      array_unshift ($lines, Fgets ($fp));
    }
  Return Array_slice ($lines, 0, $n);
}
Var_dump (Tail (fopen ("Access.log", "r+"), 10);

Method Two:

Or in a fseek way from the end of the file to read, but at this time is not a one read, but a piece of reading, each read a piece of data, the read data in a buf, and then through the number of line breaks (n) to determine whether the last $num row of data has been read. Implementation code is as follows

Complete code Execution time consuming 0.0009 (s).

$fp = fopen ($file, "R");
$line = ten;
$pos =-2;
$t = "";
$data = "";
while ($line > 0) {while
  ($t!= "n") {
    fseek ($fp, $pos, seek_end);
    $t = fgetc ($fp);
    $pos-;
  }
  $t = "";
  $data. = Fgets ($fp);
  $line-;
}
Fclose ($FP);
Echo $data

Thank you for reading, I hope to help you, thank you for your support for this site!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.