PHP to read the x row of the large file to the Y-line implementation code _php tips

Source: Internet
Author: User
Need to read a few lines of a file, but the file is relatively large, so I studied the next PHP read a few lines of the contents of the method, wrote a method, the code is as follows (added note):
If the cached file can be saved on a single line, and the algorithm reads the specified number of rows, it will naturally be much faster than the entire read out selection. But PHP seems to be weak in this area, not very good operation. Even if the use of splfileobject is still not particularly desirable, memory pressure exists.

Copy Code code as follows:

$FP->seek ($startLine-1);


After testing, this line of code in 8MB text to go to the last row, memory footprint of 49KB, is not bad. Instead of using the fgets skipped mode with the Fopen method, it costs 29KB of RAM, fopen still prevails.

Copy Code code as follows:

function Getfilelines ($filename, $startLine = 1, $endLine =, $method = ' rb ') {
$content = Array ();

if (Version_compare (php_version, ' 5.1.0 ', ' >= ')) {//Judge PHP version (because you want to use splfileobject,php>=5.1.0)
$count = $endLine-$startLine;
$fp = new Splfileobject ($filename, $method);
$FP->seek ($startLine-1); Go to Nth row, the Seek method parameter counts starting at 0
for ($i = 0; $i <= $count; + + $i) {
$content [] = $fp->current (); Current () Gets the contents of the line
$FP->next (); Next line
}
else {//php<5.1
$fp = fopen ($filename, $method);
if (! $fp)
Return ' Error:can not read file ';
for ($i = 1; $i < $startLine + + $i) {//Skip front $startline Line
Fgets ($FP);
}

for ($i; $i <= $endLine; + + $i) {
$content [] = Fgets ($FP); Read File line contents
}
Fclose ($FP);
}
Return Array_filter ($content); Array_filter filter: False,null, "
}


The effect is good, splfileobject class function is better.

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.