【问题标题】:List items from a .txt file using PHP使用 PHP 列出 .txt 文件中的项目
【发布时间】:2015-05-27 19:42:07
【问题描述】:

我有一个文本文件“textlist.txt”,其中包含由换行符“br”分隔的项目列表。 如何使用 PHP 在 html 中的有序列表中显示该列表?

文本文件内容:

item1
item2
item3

想用php这样显示

<li>item1</li>
<li>item2</li>
<li>item3</li>

我知道如何读取文件,但不会将 .txt 的内容填充到 html 有序列表中。

这就是我所拥有的

$myFile = "images/covers/lists/testlist.txt";
$fh = fopen($myFile, 'r');
$theData = fgets($fh);
fclose($fh);
echo $theData;

列表中的所有封面都是使用 glob 函数从包含封面图像的文件夹中提取的。现在我正在尝试使用 .txt 文件来标记每个封面(标题)。现在只列出 .text 文件中的最后一项

    <?php $thumbs= glob( "images/covers/13colonies/*.jpg"); ?>
          <?php if(count($thumbs)) { natcasesort($thumbs);                      
            foreach($thumbs as $thumb) { ?>

     <?php $content = file('images/covers/lists/testlist.txt');
     foreach ($content as $line)  ?>

          <li>
          <img src="<?php echo $thumb ?>" width="80%" alt="images" />
                <h5 class="title"><?php echo $line ?></h5>
          </li>

          <?php }} else { echo "Sorry, no images to display!"; } ?>

【问题讨论】:

  • 使用file() 和一个循环或implode()

标签: php html file


【解决方案1】:
$content = file('path/to/file.txt');

foreach ($content as $line) {
    echo ('<li>' . $line . '</li>);
}

file() 方法将文件的内容读取到一个数组中,每一行都作为自己的元素。然后,您可以遍历数组并对每一行做任何您想做的事情。

链接到文档here

【讨论】:

  • 您可能还想将标志:FILE_IGNORE_NEW_LINES 添加到 file(),否则他仍然在每个元素的末尾有换行符。
【解决方案2】:
$data = file_get_contents('file.txt');

$array = explode("\n" , $data);

foreach ($array as $line) {
     echo "<li>$line</li>";
}

【讨论】:

    【解决方案3】:

    使用正则表达式:

    echo preg_replace("/.+/", "<li>$0</li>", file_get_contents('file.txt'));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-15
      • 2011-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-08
      相关资源
      最近更新 更多