Buddhika Priyabhashana
Buddhika Priyabhashana

Reputation: 333

How to retrieve data from log files using linux commands and add to array

I have a log file with content like this

2018/01/14 12:27:27|get_offers|ok|1678537191|64.233.173.132|info=wifi
2018/01/14 12:27:27|get_offers|ok|1678537191|64.233.173.132|info=wifi
2018/01/14 12:27:27|get_offers|ok|1678537191|64.233.173.132|info=wifi

I'm trying to retrieve data/ offer/ status/ number/ IP separately one by one. I'm using PHP Yii framework for that and in the program running linux commands.

Commands

 $dateCmd = "cat " . $file_names_str . "| awk -F '|' '{ print $1}'";
 $descCmd = "cat " . $file_names_str . "| awk -F '|' '{ print $2}'";
 $statusCmd = "cat " . $file_names_str . "| awk -F '|' '{ print $3}'";
 $mobileCmd = "cat " . $file_names_str . "| awk -F '|' '{ print $4}'";
 $ipCmd = "cat " . $file_names_str . "| awk -F '|' '{ print $5}'";

Execution Part

 $date = shell_exec($dateCmd);
 $desc = shell_exec($descCmd);
 $status = shell_exec($statusCmd);
 $mobile = shell_exec($mobileCmd);
 $ip = shell_exec($ipCmd);

And finally i want a array like this.and encode as JSON. following array contains dummy data.

$rec = [
            [
                'date' => '2018-02-01',
                'desc' => 'test descrip',
                'status' => 'true',
                'mobile' => '2145786695',
                'ip' => '127.168.0.1',
            ],
            [
                'date' => '2018-02-01',
                'desc' => 'test descrip2',
                'status' => 'true',
                'mobile' => '2145786695',
                'ip' => '127.168.0.1',
            ],
            [
                'date' => '2018-02-01',
                'desc' => 'test descrip2',
                'status' => 'true',
                'mobile' => '2145786695',
                'ip' => '127.168.0.1',
            ],

        ];


        $enc =  CJSON::encode($rec);
        echo $enc;

But in this case it do not retrieve data as i wish. I'm new to linux and i just want to get records line by line like this image. expected output

please help me to solve this.

Upvotes: 1

Views: 146

Answers (1)

Erik Kalkoken
Erik Kalkoken

Reputation: 32737

One easy solution in PHP:

$lines = file("logfile.log");
foreach ($lines as $line)
{
  $parts = explode("|", $line);
  $result[] = [
    'date' => $parts[0],
    'desc' => $parts[1],
    'status' => $parts[2],
    'mobile' => $parts[3],    
    'ip' => $parts[4],
    'info' => $parts[5]
  ];
}

header("Content-type:application/json");
echo json_encode($result);

Upvotes: 1

Related Questions