[PHP] Reading file to array

Discussion in 'Web Design & Coding' started by vern, Jul 25, 2005.

  1. vern

    vern Dominus Political User Folding Team

    Messages:
    1,571
    Location:
    Minnesota, USA
    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?
     
  2. Khayman

    Khayman I'm sorry Hal... Political User Folding Team

    Messages:
    5,518
    Location:
    England
    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
     
    vern likes this.
  3. Geffy

    Geffy Moderator Folding Team

    Messages:
    7,805
    Location:
    United Kingdom
    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($fp1024); $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
     
    vern likes this.
  4. LordOfLA

    LordOfLA Godlike!

    Messages:
    7,027
    Location:
    Maidenhead, Berkshire, UK
    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 :)
     
  5. vern

    vern Dominus Political User Folding Team

    Messages:
    1,571
    Location:
    Minnesota, USA
    Thanks. I'll test it out and get back.