使用PHP解析文件中的行 [英] Parse lines in file using PHP

查看:44
本文介绍了使用PHP解析文件中的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从现有的.log文件(或.txt文件,没关系)中绘制数据图.

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

文件的组织方式如下.

Unixepochtime value value.\n
Unixepochtime value value value value

第一行是不同的,因为它在时间之后仅具有两个值,而随后的所有行(可能超过200行)都与上面看到的第二行完全相同.

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.

对于文件中的第二个值,它需要具有与其所在行相同的unixepochtime,但必须以上述格式在另一个字符串中写入.

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.

这也可以用于行数未知的文件吗?我正在使用Flot,如果有帮助的话.这段时间之后,此代码还可以用于仅具有一个值的文件吗?

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?

推荐答案

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

这篇关于使用PHP解析文件中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆