[PHP] Reading file to array

vern

Dominus
Political Access
Joined
2 Mar 2002
Messages
1,572
I can read an entire file into an array using file(). Does anyone know how to read the a specified number of lines into an array instead of the entire file?
 
You could use file_get_contents to get the contents into a string and specifiy the max number of bytes, then use explode to get it into an array

or just get the array with file and and the loop through it x times and copy it to another array

or use fopen and fgets to get one line of the file at a time and loop until x lines
 
if you just want to read x number of lines then use something like

PHP:
<?php
define('MAX_LINES', 100);
$fp = @fopen("/path/to/file");
$array_lines = array();
for ($i = 0; !feof($fp) && $i < MAX_LINES && $line = fgets($fp, 1024); $i++)
{
    $array[] = $line;
}
?>

This should work, I havent really tested it though, but the Code analyser in the Zend Development Environment didnt chuck up anything syntactically wrong with the code
 
I have a functions somewhere I knocked up that workks line pascals readln funtion, once I tidied up the office I'll dig it out and post it :)
 
Thanks. I'll test it out and get back.
 

Members online

No members online now.

Latest profile posts

Also Hi EP and people. I found this place again while looking through a oooollllllldddd backup. I have filled over 10TB and was looking at my collection of antiques. Any bids on the 500Mhz Win 95 fix?
Any of the SP crew still out there?
Xie wrote on Electronic Punk's profile.
Impressed you have kept this alive this long EP! So many sites have come and gone. :(

Just did some crude math and I apparently joined almost 18yrs ago, how is that possible???
hello peeps... is been some time since i last came here.
Electronic Punk wrote on Sazar's profile.
Rest in peace my friend, been trying to find you and finally did in the worst way imaginable.

Forum statistics

Threads
62,015
Messages
673,494
Members
5,623
Latest member
AndersonLo
Back