【问题标题】:PHP reading from file multiple lines, different first wordsPHP从文件中读取多行,不同的第一个单词
【发布时间】:2013-06-17 15:12:20
【问题描述】:

我正在尝试从 php 中的 txt 文件中读取。我能够打开文件并逐行正确显示,但我想根据第一个单词做出决定。例如,如果在文本文件中该行以:

Something1:这是一个测试

它会输出那个字符串,但“Something1:”会是粗体并且颜色不同

Something2:这是一个测试2

这也是粗体和颜色。所以可以说我希望所有标记为“Something1:”的内容都以粗体和红色输出,但我希望所有“Something2:”都以粗体和绿色输出。有没有办法做到这一点。

$file = fopen($message_dir, "a+") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while (!feof($file))
{
    if (strpos(fgets($file), "Something1") == 0)
    {
        echo "<font color='#686868'><b>".fgets($file)."</b></font><hr />"."<br />";
    }
    else
    {
        echo "<font color='#fc0c87'><b>".fgets($file)."</b></font><hr />"."<br />";   
    }
}
fclose($file);

这是我前进的方向,但我确信有一种更简单更有效的方法。首先,这将整个句子加粗并着色,其次,我认为 fgets 自动递增或其他什么,因为它正确执行了 if 语句,但随后它打印下一行而不是它为其执行 if 语句的行。但这是我的第一个想法,检查单词是否位于字符串的位置 0。

【问题讨论】:

  • 为什么要以附加模式打开文件?您可以使用'r' 作为模式。
  • btw 文件中有多少行?很多吗?

标签: php string file fopen


【解决方案1】:

主要问题是fgets()每次调用它时都会读取另一行,所以如果你想重用它,你需要将它的值保存在一个中间变量中:

$line = fgets($file);

if (strpos($line, 'Something1') === 0) {
    $format = '<font color="#686868"><b>%s</b></font><hr /><br />';
} else {
    $format = '<font color="#fc0c87"><b>%s</b></font><hr /><br />';
}

echo sprintf($format, htmlspecialchars($line, ENT_QUOTES, 'UTF-8'));

另外,您正在以附加模式打开文件,但您从未写入:

$file = fopen($message_dir, "r") or exit("Unable to open file!");

【讨论】:

  • 谢谢!我无法让你的工作,但后来我注意到 if 语句有 === 并且一旦我添加它就可以了。感谢关于追加模式的提示,原因是因为接下来会追加,我只是先专注于阅读
【解决方案2】:

您需要从文件中读取到缓冲区变量中,每次您从文件中读取新数据时,在您的情况下,前面的数据都会“丢失”。

$file = fopen($message_dir, "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while (!feof($file))
{
    $currentLine = fgets($file);
    if (strpos($currentLine, "Something1") == 0)
    {
        echo "<font color='#686868'><b>$currentLine</b></font><hr /><br />";
    }
    else
    {
        echo "<font color='#fc0c87'><b>$currentLine</b></font><hr /><br />";   
    }
}
fclose($file);

我不会使用字体标签等,而是依赖css:

$file = fopen($message_dir, "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
echo "<ul>\n";
while (!feof($file))
{
    $currentLine = fgets($file);
    if (strpos($currentLine, "Something1") == 0)
    {
        echo "<li class="Some1">$currentLine</li>\n";
    }
    else
    {
        echo "<li>$currentLine</li>\n";   
    }
}
echo "</ul>\n";
fclose($file);

由于您要输出一个列表,我会使用一个无序列表并通过 css 进行格式化,如下所示:

ul > li {
    color: #fc0c87;
    font-weight: bold;
    list-style: none;
}

ul > li.Some1 {
    color: #686868;
}

通过对 ul &gt; li 规则进行适当的更改,您可以利用 css 来更好地调整外观,而不是使用 hr/br 标签。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-18
    • 2015-03-14
    • 2018-08-05
    • 2012-09-23
    • 1970-01-01
    相关资源
    最近更新 更多