Parse lines in file using PHP

2019-09-09 19:25发布

I am trying to graph data from existing .log files (or .txt file, it doesn't matter).

The file is organised like this.

Unixepochtime value value.\n
Unixepochtime value value value value

The first line is different as it only has two values after the time, whereas all the following lines (200+ maybe) are exactly the same as the second line seen above.

However these last two values in the second line and following lines are not needed.

The output needs to be in a file or string in the following manner:

[unixepochtime, value], [unixepochtime, value]

Of course there will be one for every line though, so to make that clear, the string above would cover two lines of data.

For the second value in the file, it needs to have the same unixepochtime as was on its line, but be written in the format above in another string.

Can this work for files with an unknown amount of lines also? I'm using Flot, if that helps. Can this code also work for files with only one value following the time please?

1条回答
Lonely孤独者°
2楼-- · 2019-09-09 20:06
<?php
$pathToLogfile = 'logfile.txt';

// Check if file exists.
if(!file_exists($pathToLogfile)) {
  echo('Can not find log file');
  exit;
}

// Extract separate lines.
$logEntries = file($pathToLogfile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMTPY_LINES);
// Build code in lines.
$entries = array();
foreach($logEntries as $logEntry) {
  // Split logline into separate values by whitespace.
  $logLineParts = explode(" ", $logEntry);

  // Check if unix epoch is set.
  if(!isset($logLineParts[0])) {
    echo('Missing unix timestamp...');
    continue;
  }
  $unixTimestamp = $logLineParts[0];

  // Check for all values but unix timestamp.
  for($i = 1; $i < count($logLineParts); ++$i) {
    $entries[] = '[' . $unixTimestamp .', '. $logLineParts[$i] .']';
  }
}

echo('Following log items found: '. implode(', ', $entries));
?>

I commented it so I hope you can learn from it (what is the most important thing here!) Should work - although untested...

查看更多
登录 后发表回答