我刚刚创建了一个脚本来获取ip,主机名和日期并将其放入文本文件中。我想创建另一个脚本,将这些信息显示在带有一些表的.php中,以便于阅读。
这是我用来写入完美的文件的代码。我只是不知道如何解析它来做我想做的事。
$logFile = 'IPLog.txt';
$fh = fopen($logFile,'a') or die("can't open file");
$ip = $_SERVER['REMOTE_ADDR'];
$fullhost = gethostbyaddr($ip);
$stringData = date('m/d/y | h:ia') . " - " . $ip . ":" . $fullhost . "\n";
fwrite($fh, $stringData);
fclose($fh);
输出看起来像这样..
04/06/13 | 02:53 pm - xxx.xxx.xxx.xxx:xxx.comcast.net
我正在等待脚本读取文件并将其显示在诸如。
之类的表格中IP Address | Hostname | Date | Time
----------------|-------------------|-------------|-----------------------------
xxx.xxx.xxx.xx | xxx.comcast.net | 04/06/13 | 02:53pm
--------------------------------------------------------------------------------
xxx.xxx.xxx.xx | xxx.comcast.net | 04/06/13 | 02:53pm
--------------------------------------------------------------------------------
xxx.xxx.xxx.xx | xxx.comcast.net | 04/06/13 | 02:53pm
--------------------------------------------------------------------------------
xxx.xxx.xxx.xx | xxx.comcast.net | 04/06/13 | 02:53pm
--------------------------------------------------------------------------------
所以我希望它只是制作一个漂亮的小桌子来显示信息,这样我就可以快速检查它并且看起来不错。
我想要这个没有任何特别的原因。我只是用它来解析如何解析文本文件。我从来没有擅长它,真的想知道它是如何完成的。如果我也愿意,我可以将它用于其他事情。
答案 0 :(得分:0)
将当前输出更改为:04/06/13 - 02:53pm - xxx.xxx.xxx.xxx - www.comcast.net
。
这将使以后更容易解析。
因此,在当前文件中,您必须更改以下行:
$stringData = date('m/d/y - h:ia') . " - " . $ip . " - " . $fullhost . "\n";
现在要在表格中显示数据,您可以使用以下内容:
$logFile = 'IPLog.txt';
$lines = file($logFile); // Get each line of the file and store it as an array
$table = '<table border="1"><tr><td>Date</td><td>Time</td><td>IP</td><td>Domain</td></tr>'; // A variable $table, we'll use this to store our table and output it later !
foreach($lines as $line){ // We are going to loop through each line
list($date, $time, $ip, $domain) = explode(' - ', $line);
// What explode basically does is it takes a delimiter, and a string. It will generate an array depending on those two parameters
// To explain this I'll provide an example : $array = explode('.', 'a.b.c.d');
// $array will now contain array('a', 'b', 'c', 'd');
// We use list() to give them kind of a "name"
// So when we use list($date, $time, $ip, $domain) = explode('.', 'a.b.c.d');
// $date will be 'a', $time will be 'b', $ip will be 'c' and $domain will be 'd'
// We could also do it this way:
// $data = explode(' - ', $line);
// $table .= '<tr><td>'.$data[0].'</td><td>'.$data[1].'</td><td>'.$data[2].'</td><td>'.$data[3].'</td></tr>';
// But the list() technique is much more readable in a way
$table .= "<tr><td>$date</td><td>$time</td><td>$ip</td><td>$domain</td></tr>";
}
$table .= '</table>';
echo $table;