Search code examples
phpparsingexplodedelimiterlogfiles

single line text log file parsing


So i have a log/txt file wich contains the following :

31 dec. 2014 11:56 - UserA: Hi31 dec. 2014 11:56 - UserB: Hi to you31 dec. 2014 11:56 - UserA: Whats your name?31 dec. 2014 11:57 - UserB: Nancy

Im trying to get this into a more readable format..... So im trying the following :

<?php
//load the logfile
$txt_file    = file_get_contents('test.txt');
$txtfile2 = preg_split( "/ ( |:) /", $txt_file );
$rows = explode("\n", $txtfile2[0]);

foreach($rows as $row => $data)
{
$row_data = explode(':', $data);


$info[$row]['when']           = $row_data[0];
$info[$row]['name']         = $row_data[1];
$info[$row]['description']  = $row_data[2];


//display data
echo ' WHEN: ' . $info[$row]['when'] . '<br />';
echo ' WHO: ' . $info[$row]['name'] . '<br />';
echo ' MESSAGE: ' . $info[$row]['description'] . '<br /><br />';

}
?>

This works partially.... When executed the output would be :

WHEN: 31 dec. 2014 11 WHO: 56 - UserA MESSAGE: Hi

WHEN: 31 dec. 2014 11 WHO: 56 - UserB MESSAGE: Hi to you

This is close to what i want, but as you can see, because im using the delimiter ":" it will also cut the time and place the minutes in the who. How can i explode on the second ":" only?

i hope this makes sense?


Solution

  • See how this works for you

        <?php
        $filename = "logfile.txt"; //data file to open
        $fp = fopen( $filename, "r" ) or die("Couldn't open $filename");
        while ( ! feof( $fp ) )
            {
            $line = fgets( $fp, 1024 );
            $line_array = preg_split("/[:-]+/", $line);
            $line_timestamp = $line_array[0] . ":" . $line_array[1];
            $line_user = $line_array[2];
            $line_message = $line_array[3];
            echo ' WHEN: ' . $line_timestamp . '<br />';
            echo ' WHO: ' . $line_user . '<br />';
            echo ' MESSAGE: ' . $line_message . '<br /><br />';
            }
       ?>