2012-08-05 57 views
1

有人可以幫助我嗎?PHP forech循環讀取文件,創建數組和打印文件名

我有一些文件(無extention)

/模塊/郵件/模板

隨着這些文件的文件夾:

  • 測試
  • test2的

我想先循環並讀取文件名(test和test2)並將它們打印到我的ht中毫升表格作爲下拉項目。這是有效的(表單html標籤的其餘部分在上面和下面的代碼下面,這裏省略)。

但我也想讀取每個文件的內容,並將內容分配給一個var $內容,並將其放入一個我可以稍後使用的數組中。

這是我如何努力實現這一目標,沒有運氣:

foreach (glob("module/mail/templates/*") as $templateName) 
     { 
      $i++; 
      $content = file_get_contents($templateName, r); // This is not working 
      echo "<p>" . $content . "</p>"; // this is not working 
      $tpl = str_replace('module/mail/templates/', '', $templatName); 
      $tplarray = array($tpl => $content); // not working 
      echo "<option id=\"".$i."\">". $tpl . "</option>"; 
      print_r($tplarray);//not working 
     } 

任何幫助,將不勝感激:)

+0

什麼錯?解釋你的意思是「不工作」 – SomeKittens 2012-08-05 01:00:12

+0

var_dump($ templateName);就在你的循環的頂部。我的猜測是glob()沒有拾取具有該模式的任何文件。 – 2012-08-05 01:03:27

+0

循環運行但不會回顯$ content var,並且print_r不會打印。所以我認爲它沒有迴應,或者我做錯了什麼。也許有更好的方法來做到這一點。但是我不知道它出錯的地方,因爲它只是沒有錯誤地運行,但不會做我想要的。 – Bolli 2012-08-05 01:04:23

回答

1

此代碼爲我工作:

<?php 
$tplarray = array(); 
$i = 0; 
echo '<select>'; 
foreach(glob('module/mail/templates/*') as $templateName) { 
    $content = file_get_contents($templateName); 
    if ($content !== false) { 
     $tpl = str_replace('module/mail/templates/', '', $templateName); 
     $tplarray[$tpl] = $content; 
     echo "<option id=\"$i\">$tpl</option>" . PHP_EOL; 
    } else { 
     trigger_error("Cannot read $templateName"); 
    } 
    $i++; 
} 
echo '</select>'; 
print_r($tplarray); 
?> 
+0

感謝它爲我工作 – Bolli 2012-08-05 01:32:24

1

初始化循環外的數組。然後在循環內分配它的值。不要嘗試打印陣列,直到您處於循環之外。

撥打file_get_contents時出現r錯誤。把它拿出來。 file_get_contents的第二個參數是可選的,如果使用它,應該是一個布爾值。

檢查file_get_contents()未返回FALSE如果嘗試讀取文件時發生錯誤,則返回該值。

你有一個錯字,你指的是$templatName而不是$templateName

$tplarray = array(); 
foreach (glob("module/mail/templates/*") as $templateName) { 
     $i++; 
     $content = file_get_contents($templateName); 
     if ($content !== FALSE) { 
      echo "<p>" . $content . "</p>"; 
     } else { 
      trigger_error("file_get_contents() failed for file $templateName"); 
     } 
     $tpl = str_replace('module/mail/templates/', '', $templateName); 
     $tplarray[$tpl] = $content; 
     echo "<option id=\"".$i."\">". $tpl . "</option>"; 
} 
print_r($tplarray); 
+0

'file_get_contents'中的'r'會來自['fopen'](http://php.net/manual/en/function.fopen.php)。 – 2012-08-05 01:12:21

+0

對不起,我開始使用fopen,並忘記改變它。 非常感謝您的幫助。現在我再次獲得文件名,但仍然沒有print_r和echo $ content的輸出 – Bolli 2012-08-05 01:20:36

+0

此外,使用'echo' ';'或'echo「」;'。 – 2012-08-05 01:21:14