2013-07-08 38 views
0

我有我給定的輸入保存到一個文本文件形式返回false,
但我有麻煩從已保存的文件中讀取:與fgets(),即使文件不爲空

while(!feof($fileNotizen)) { 
$rawLine = fgets($fileNotizen); 
if($rawLine==false) { 
    echo "An error occured while reading the file"; 
} 


$rawLine似乎總是假的,即使我之前使用此功能,填補了文本文件:

function addToTable($notizFile) { 
fwrite($notizFile, $_POST["vorname"]." ".$_POST["nachname"]."#"); 
$date = date(DATE_RFC850); 
fwrite($notizFile, $date."#"); 
fwrite($notizFile, $_POST["notiz"].PHP_EOL); 
} 


後,我提交形式並獲取錯誤消息,如果我檢查文本文件,一切都在那裏,所以該功能正常工作。

如果它的價值,我打開該文件使用此命令:

$fileNotizen = fopen("notizen.txt", "a+"); 

可能的問題是指針已經在文件的結尾,因此返回false?

回答

1
$fileNotizen = fopen("notizen.txt", "a+"); 

a+打開進行讀/寫,但地方文件指針指向END。因此,您必須首先從fseek()開始,或者查看fopen() flags並根據您的需求更明智地選擇。使用fseek($fileNotizen, 0, SEEK_SET);來倒帶文件。

+0

這似乎是我所需要的,但加入這個確實不改變輸出,我也試過'快退($ fileNotizen)'沒有結果。 –

+0

@Big_Chair使用'fseek($ fileNotizen,0,SEEK_SET);'倒回文件。並確保文件實際上打開了'if($ fileNotizen)'。並使用'__DIR__'來使用絕對路徑。 – CodeAngry

+0

看來我的問題一定是由別的原因引起的,因爲這似乎也沒有幫助。 儘管謝謝你的幫助! –

0

要讀/獲取文件的內容試試這個功能:

function read_file($file_name) { 
     if (is_readable($file_name)) { 
      $handle = fopen($file_name, "r"); 
      while (!feof($handle)) { 
       $content .= fgets($handle); 
      } 
      return !empty($content) ? $content : "Empty file.."; 
     } else { 
      return "This file is not readable."; 
     } 
    } 

,如果你想看到在單獨的行顯示的文件的內容,然後使用<pre></pre>標籤是這樣的:

echo "<pre>" . read_file("notizen.txt") . "</pre>"; 

如果你想寫/添加內容到文件然後嘗試這個功能:

function write_file($file_name, $content) { 
     if (file_exists($file_name) && is_writable($file_name)) { 
      $handle = fopen($file_name, "a"); 
      fwrite($handle, $content . "\n"); 
      fclose($handle); 
     } 
    }   

你可以使用它像這樣:

$content = "{$_POST["vorname"]} {$_POST["nachname"]}#" . date(DATE_RFC850) . "#{$_POST["notiz"]}"; 
write_file("notizen.txt", $content);