How to tell php to begin reading a file at a particular 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
User avatar
infolock
DevNet Resident
Posts: 1708
Joined: Wed Sep 25, 2002 7:47 pm

How to tell php to begin reading a file at a particular line

Post by infolock »

Hello. I am currently just learning php so i decided to write a log parser. I've asked a lot of questions and have gotten great results from the users here. Now, I have a new question :)

My log file has data at the beginning of it that i really don't need to parse. the 4th line starts where the headers are, and then the 5th line consists of the actual values. How do i tell php to read the 4th line for only the headers, and then read from lines 5 to EOF for t he values ?

Thanks :P
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

If you're using file then you can do something like:

Code: Select all

$file_contents = file($path_to_file);

foreach ($file_contents as $num => $line_data) {
    $line_no = $num + 1;

    if ($line_no == 4) {
        // do header stuff
    } elseif ($line_no > 4) {
        // do main content stuff
    }
}
Mac
User avatar
infolock
DevNet Resident
Posts: 1708
Joined: Wed Sep 25, 2002 7:47 pm

Post by infolock »

Thanks mac 8)

btw, how do you make your code look color coated instead of mono? Inquiring minds 8O
User avatar
DuFF
Forum Contributor
Posts: 495
Joined: Tue Jun 24, 2003 7:49 pm
Location: USA

Post by DuFF »

click the PHP button right above replys, paste your code and hit it again. Alternatively you could just put [ php] and [ /php] without the spaces.
Last edited by DuFF on Mon Nov 03, 2003 3:36 pm, edited 1 time in total.
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

Use the PHP BBCode tags, put your code between

Code: Select all

and
tags instead of code ones.


Mac
User avatar
infolock
DevNet Resident
Posts: 1708
Joined: Wed Sep 25, 2002 7:47 pm

Post by infolock »

sweet thanks
User avatar
JAM
DevNet Resident
Posts: 2101
Joined: Fri Aug 08, 2003 6:53 pm
Location: Sweden
Contact:

Post by JAM »

Also, reading a file into an array will give you other usefull things to work with:

Code: Select all

clean.txt contains:
Row 1
Row 2
Row 3
Row 4
Row 5
Row 6

Code: Select all

<pre>
<?php
    $startat = 3;
    $array = file('clean.txt');
    foreach ($array as $row => $value) {
        if ($row > $startat-1) { // as arrays start at 0, this is easier to 'read'
            echo $value;
        }
    }
?>

Code: Select all

Result:
Row 4
Row 5
Row 6
Post Reply