1

我刚刚创建了一个脚本来获取 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);

输出看起来像这样..

2013 年 4 月 6 日 | 下午 2:53 - 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
--------------------------------------------------------------------------------

所以我希望它只是制作一个漂亮的小表格来显示信息,这样我就可以快速检查它并且看起来不错。

我想要这个没有任何特别的原因。我仅将其用作如何解析文本文件的示例。我从来都不擅长它,我真的很想了解它是如何完成的。因此,如果我也愿意,我可以将其用于其他事情。

4

1 回答 1

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;
于 2013-04-06T22:52:26.977 回答