2013-03-24 75 views
0
<?php 

foreach (glob("POSTS/*.txt") as $filename) 
     {  

      $file = fopen($filename, 'r') or exit("Unable to open file!"); 
      //Output a line of the file until the end is reached 


       echo date('D, M jS, Y H:i a', filemtime($filename))."<br>"; 
       while(!feof($file)) 
        { 
        echo fgets($file). "<br>"; 
        } 
      echo "<hr/>"; 
     } 
    fclose($file); 



    ?> 

所以這個PHP代碼從一個文件夾中讀取所有的文件和行中的每個文件中的行,我想它,以便讀取文件時會:爲第一行添加一個html標籤,使第一行成爲大標題,下一行正常?我如何做到這一點,得益於PHP輸入文件行做第一行頭一個標籤

+0

您可以使用[與fgets(http://php.net/manual/en/function.fgets.php)做這件事 – 2013-03-24 10:52:00

+0

你能告訴我怎麼實施它請進入我的編碼 – Josh 2013-03-24 10:52:36

回答

1

只需進入循環,這樣之前讀取一行:

echo date('D, M jS, Y H:i a', filemtime($filename))."<br>"; 
echo '<h1>' . htmlspecialchars(fgets($file)) . '</h1>'; 
while (!feof($file)) { 
    echo htmlspecialchars(fgets($file)) . '<br/>'; 
} 

需要注意的是這隻能是偶然在一個空文件的情況下,如果fgets將返回false ,這將顯示爲''。你能趕上,通過虛假明確地檢查:

$firstLine = fgets($file); 
if ($firstLine == false) { 
    echo '<h1>' . htmlspecialchars($firstLine) . '</h1>'; 
} 
+0

很實際的想法... +1 – Ihsan 2013-03-24 11:04:24

相關問題