首页 > 解决方案 > 如何从文本文件中获取每一行并将其放入网站表中?

问题描述

我有一个文本文件,其中包含可变数量的行,每行包含 3 个内容,一个 IP、浏览器信息和一个日期。基本上它是一个包含这些内容的访问者日志。

我想取一行,获取每个单独的部分并替换 html 文档表中的行。截至目前,我只能从文件中获取第一行。

当我试图在遍历每一行的while循环中打印一些东西以查看它是否实际上多次通过它时,它没有。它只回响一次,它跑了一圈,读了一行,然后停止。

文本文件包含例如:

日期、浏览器信息和 IP。

<?php
// file path
$path = './visitors.txt';
$html = file_get_contents("log.html");

$visitor_log = fopen($path, 'r');
if(flock($visitor_log, LOCK_SH)){
  // Loop genom alla rader i visitors.txt
  while (($line = fgets($visitor_log)) !== false) {
    $html_pieces = explode("<!--==xxx==-->", $html, 3); 
    $string_split = explode("--", $line, 3); 
    $html = str_replace("---date---", $string_split[0], $html); 
    $html = str_replace("---browser---", $string_split[1], $html); 
    $html = str_replace("---ip---", $string_split[2], $html); 
  }
  fclose($visitor_log);
}else{
die("Error! Couldn't read from file.");
}
echo $html;
?>

我不知道为什么循环不遍历整个文件。有没有办法只回显每一行,看看它是否真的可以读取所有行?

编辑:我刚试过

echo $html;

在while循环中,它会打印出第一行三遍,所以我相信它会遍历所有三行,但它没有得到新数据。是否与以下内容有关:

$html = file_get_contents("log.html");

没有得到更新?

编辑:表格的 html 代码

<table cellspacing="0" cellpadding="10" border="1" width="100%">
  <thead>
    <tr>
      <th align="left">Dare</th>
      <th align="left">Browser</th>
      <th align="left">IP</th>
    </tr>
  </thead>
  <tbody>
    <!--==xxx==-->
    <tr>
      <td align="left">---date---</td>
      <td align="left">---browser---</td>
      <td align="left">---ip---</td>
    </tr>
    <!--==xxx==-->
  </tbody>
</table>

标签: phphtmlstr-replaceexplode

解决方案


问题在于您如何将数据添加到您的$html

$html = str_replace("---date---", $string_split[0], $html); 

这将用当前正在处理的行的日期替换字符串中的---date---每个实例。$html如果$html是单行模板,则表示将其转换为第一行的一行数据。那会很好用。

但是对于下一行,替换字符串---date---等不再出现$html-$html现在包括您的第 1 行数据。因此,str_replace()找不到任何要替换的东西,实际上也不会做任何事情,除了第一行之外,您将永远看不到任何东西。

最好的解决方案是将模板和生成的结果分开:

$html = file_get_contents("log.html");

// Split up your html into header, data row, and the bottom
$html_pieces = explode("<!--==xxx==-->", $html, 3); 

// Show the table header
echo $html_pieces[0];

$path = './visitors.txt';
$visitor_log = fopen($path, 'r');

while (($line = fgets($visitor_log)) !== false) {
    $string_split = explode("--", $line, 3); 

    // Generate a new line of $output from the data row of your $html_pieces
    $output = str_replace("---date---", $string_split[0], $html_pieces[1]); 
    $output = str_replace("---browser---", $string_split[1], $output); 
    $output = str_replace("---ip---", $string_split[2], $output); 

    // And display, line-by-line
    echo $output;
}

// All done, finish off your table
echo $html_pieces[2];

推荐阅读