通过PHP解析日志文件

时间:2017-03-02 07:06:34

标签: php parsing logging

我尝试解析这个日志文件,但我没有让它工作

logfile看起来像这样

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

我需要它将它解析为数组,日期,时间,更新,ip1,ip2,标志

希望有人能帮助我

2 个答案:

答案 0 :(得分:2)

您可以执行以下操作: -

log_file.log(我为我的编码而创建): -

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

现在php代码: -

<?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

我本地结束的输出: - http://i.share.pho.to/116cc350_o.png

答案 1 :(得分:1)

试试这个

$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
        )

)