单行文本日志文件解析

时间:2015-02-24 13:38:35

标签: php parsing explode delimiter logfiles

所以我有一个log / txt文件,其中包含以下内容:

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

我试图将其变为更易读的格式..... 所以我试着以下:

<?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 />';

}
?>

这部分工作.... 执行时输出为:

时间:12月31日。 2014 11 世卫组织:56 - UserA 消息:嗨

时间:12月31日。 2014 11 世卫组织:56 - 用户B. 消息:嗨,你

这接近我想要的,但正如你所看到的,因为我正在使用分隔符&#34;:&#34;它还会缩短时间并将分钟放在谁身上。 我怎么能在第二个&#34;上爆炸:&#34;仅?

我希望这有道理吗?

1 个答案:

答案 0 :(得分:0)

了解这对您有何帮助

    <?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 />';
        }
   ?>