Page 1 of 1

Read php file starting at line

Posted: Fri May 15, 2009 11:55 am
by aderes
Hello:

Does anyone know how to read a file starting at a specific line?

Thanks

Re: Read php file starting at line

Posted: Fri May 15, 2009 12:14 pm
by ldougherty
http://us.php.net/file_get_contents

example..

Code: Select all

 
<?php
// Read 14 characters starting from the 21st character
$section = file_get_contents('./people.txt', NULL, NULL, 20, 14);
var_dump($section);
?>
 
alternately if you wanted to read a file line by line you can do so into an array and then just reference the array lines you want.

http://us.php.net/manual/en/function.file.php

Re: Read php file starting at line

Posted: Fri May 15, 2009 12:35 pm
by aderes
Hi ldougherty:

Thanks for your reply. I was hoping to be able to start at a certain line not a certain character position, as I won't be able to tell how many characters are in a line. Currently I'm simply looping though a bunch or gets before I start storing the data in an array. It works but seems rather clunky.

Re: Read php file starting at line

Posted: Fri May 15, 2009 1:01 pm
by crazycoders
No it's actually normal... there are no function that scans X line from the start so the only way is that you implement it yourself by doing fgets to skip x lines and then read the rest one by one using fgets...

You have 3 ways to read a file line by line, 2 of which are useful only with small files:

- file_get_contents() returns the whole content as a string, then you can explode it but it is highly memory ineffective...
- file() returns the whole content as a string array, each item being a line, slightly more efficient but still copies the WHOLE file in memory, not a good think for files larger than a few K if you aren't going to use it.
- fopen()/fgets() reads data line by line keeping your memory clean as much as you let it be (if you decide to store all lines in memory that wasn't a good way to go, you'll be wasting more cycles read for nothing while file() would have been better!

Re: Read php file starting at line

Posted: Fri May 15, 2009 3:28 pm
by aderes
Thanks for the advice.