dongling5411 2013-12-02 10:02
浏览 24
已采纳

解析文本文件以创建有用的日志文件

On an ubuntu 10.04 server, i have a 30mb log file from php.

Unfortunately the log looks like this:

...)
Array
(
    [calid] => 3114
    [email] => somemail@hotmail.com
    [firstname] => John
    [lastname] => Smith
    [address] => Lorem ipsum.
    [city] => Lorem
    [postcode] => 1345
    [date] => 01-12-2013
)
Array
(
    [calid] => 3111
    [firstname] => Lisa
    [lastname] => Smith
    [address] => Lorem ipsum.
    [city] => Lorem
    [postcode] => 4110
    [email] => somemail@gmail.com
    [phone] => 12345678
    [age] => 24
    [gender] => female
    [customer] => true
    [terms] => true
    [newsletter] => true
    [date] => 01-12-2013
)
Array
(...

How can i parse this into something more useful? A csv would be nice.

  • 写回答

1条回答 默认 最新

  • douhuan1648 2013-12-02 11:12
    关注

    A raw idea that may be helpful as a start:

    $log = fopen('yourlogfile.log', 'r');
    
    $data = array();
    $key = 0;
    
    while (!feof($log)) 
    {
        $line = fgets($log);
    
        if(false !== strpos($line, 'Array'))
        {
            $key++;
            $data[$key] = array();
        }
    
        $pattern = '/\[(.*?)\] => (.+)/';
        preg_match_all($pattern, $line, $matches);
    
        if(!empty($matches[0]))
        {
            $data[$key][$matches[1][0]] = $matches[2][0];
        }
    }
    fclose($log);
    
    // var_dump($log);
    
    $csv = fopen('yourtarget.csv', 'w+');
    
    for( $i = 1; $i <= count($data); $i++) 
    {
        fputcsv($csv, $data[$i]);
    }
    fclose($csv);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Stata 面板数据模型选择
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用