The php fseek function can be used to read large files,

Source: Internet
Author: User

The php fseek function can be used to read large files,

The fseek function is the most common method for php to read large files. It does not need to read all the file content into the memory, but directly operates through pointers, so the efficiency is quite efficient. when using fseek to operate files, there are also a variety of different methods, and the efficiency may be slightly different. Below are two common methods.

Method 1:

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

It takes 0.0095 seconds to complete the code execution)

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 2:

The fseek method is used to read the last part of the file, but it is not a one-bit read, but a one-piece read. When each piece of data is read, put the read data in a buf, and then determine whether the last $ num row data has been read by the number of linefeeds (n. the implementation code is as follows:

The execution of the entire Code takes 0.0009 (s ).

$fp = fopen($file, "r");$line = 10;$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 this article. I hope it will 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.