arcronis
arcronis

Reputation: 61

Parsing Logfile via PHP

I try to parse this log file but I can't get it working.

The log file looks like this:

2017.03.02 00:29:17 UDP: 37.114.111.111:53570 -> 123.123.123.123:9987 flags: 0x00 size: 53
2017.03.02 00:29:17 UDP: 123.123.123.123:53570 -> 123.123.123.123:9987 flags: 0x18 size: 53

I need it to parse into an array , date, time , upd , ip1 , ip2 , flags

Hope anyone can help me.

Upvotes: 2

Views: 3486

Answers (2)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72269

You can do it like below:-

log_file.log (i have created for my coding sake):-

2017.03.02 00:29:17 UDP: 37.114.111.111:53570 -> 123.123.123.123:9987 flags: 0x00 size: 53
2017.03.02 00:29:17 UDP: 123.123.123.123:53570 -> 123.123.123.123:9987 flags: 0x18 size: 53

Now php code:-

<?php
$data = file("log_file.log",FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); //read the entire file to array by ignoring new lines and spaces

echo "<pre/>";print_r($data); // print output of the above line

$final_array = array(); // create an empty array

foreach ($data as $key=> $dat){ // iterate over file() generated array

    $final_data = explode(' ',$dat); //explode the data with space

    //now assign the value to corresponding indexes

    $final_array[$key]['date']  = $final_data[0];
    $final_array[$key]['time']  = $final_data[1];
    $final_array[$key]['upd']   = $final_data[2];
    $final_array[$key]['ip1']   = $final_data[3];
    $final_array[$key]['ip2']   = $final_data[5];
    $final_array[$key]['flags'] = $final_data[7];
    $final_array[$key]['size']  = $final_data[9];
}


echo "<pre/>";print_r($final_array); // print the final output

Output of my local end:-http://i.share.pho.to/116cc350_o.png

Upvotes: 2

Abdul Rafay
Abdul Rafay

Reputation: 312

try this

$file = file('<path-to-logfile>/.logfile');
$a = array();
foreach($file as $log){
    $a[] = explode (' ', $log);
}

//$a will return something like this
// you can manage this array as per your need
Array
(
    [0] => Array
        (
            [0] => 2017.03.02
            [1] => 00:29:17
            [2] => UDP:
            [3] => 37.114.111.111:53570
            [4] => ->
            [5] => 123.123.123.123:9987
            [6] => flags:
            [7] => 0x00
            [8] => size:
            [9] => 53

        )

    [1] => Array
        (
            [0] => 2017.03.02
            [1] => 00:29:17
            [2] => UDP:
            [3] => 123.123.123.123:53570
            [4] => ->
            [5] => 123.123.123.123:9987
            [6] => flags:
            [7] => 0x18
            [8] => size:
            [9] => 53
        )

)

Upvotes: 1

Related Questions