Read php file starting at line

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
aderes
Forum Newbie
Posts: 6
Joined: Wed May 06, 2009 6:34 pm

Read php file starting at line

Post by aderes »

Hello:

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

Thanks
ldougherty
Forum Contributor
Posts: 103
Joined: Sun May 03, 2009 11:39 am

Re: Read php file starting at line

Post 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
Last edited by Benjamin on Fri May 15, 2009 12:16 pm, edited 1 time in total.
Reason: Changed code type from text to php.. AGAIN!
aderes
Forum Newbie
Posts: 6
Joined: Wed May 06, 2009 6:34 pm

Re: Read php file starting at line

Post 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.
crazycoders
Forum Contributor
Posts: 260
Joined: Tue Oct 28, 2008 7:48 am
Location: Montreal, Qc, Canada

Re: Read php file starting at line

Post 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!
aderes
Forum Newbie
Posts: 6
Joined: Wed May 06, 2009 6:34 pm

Re: Read php file starting at line

Post by aderes »

Thanks for the advice.
Post Reply