以列表形式读出并显示txt文件的内容

时间:2014-05-08 14:44:51

标签: php

我有一个列出文件夹中所有txt文件的脚本。我想要做的是显示文件内容而不是文件名。但我没有成功...我尝试了readfile和filegetcontents,但我只得到.txt名称

<?php
if ($handle = opendir('../plugins/guestbook/news/')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            echo "<center><label class='tablog3a'>$file <div style='float: right;margin-top:10px;'><a href='gbremove.php?file=".$file."'><img src='images/deletegb.png' title='Verwijder afbeelding' class='clickreverse'></a></div></label></center>";
        }
    }
    closedir($handle);
}
?>

我也试过

<?php
if ($handle = opendir('../plugins/guestbook/news/')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
$txtfile = file_get_contents('$file');
            echo "<center><label class='tablog3a'>$txtfile<div style='float: right;margin-top:10px;'><a href='gbremove.php?file=".$file."'><img src='images/deletegb.png' title='Verwijder afbeelding' class='clickreverse'></a></div></label></center>";
        }
    }
    closedir($handle);
}
?>

1 个答案:

答案 0 :(得分:2)

这对我有用:

<?php 
$dir = "your_directory/"; // Your directory

if ($handle = opendir($dir)) {
  while (false != ($file = readdir($handle))) {
      // Check for .txt files
      if ($file != "." && $file != ".." && substr($file, -3) == "txt") {
        // Open file to read
        $fp = fopen($dir.$file, 'r');

        // Print contents
        echo fread($fp, filesize($dir.$file)).'<br />';
      }
  }
  closedir($handle);
}?>

欢呼声