• This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn more.

[PHP] Reading file to array

vern

Dominus
Political User
#1
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?
 

Khayman

I'm sorry Hal...
Political User
#2
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
 
#3
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
 
#4
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 :)
 

Members online

Latest posts

Latest profile posts

Hello, is there anybody in there? Just nod if you can hear me ...
Xie
What a long strange trip it's been. =)

Forum statistics

Threads
61,961
Messages
673,239
Members
89,014
Latest member
sanoravies