2016-11-23 78 views
-1

我想創建通過PHP這樣一個新的.txt文件:PHP沒有警告創建新文件:「沒有這樣的文件」

$file = 'students.txt'; 
    // opens file to load the current content 
    $current = file_get_contents($file); 
    // add new content to file 
    $current .= $_POST["name"] . " : " . $_POST["grade"] . PHP_EOL; 
    // writes content to file 
    file_put_contents($file, $current); 

它工作正常,但是當文件不存在,我得到一個警告在開始時。這不是問題,因爲php在這種情況下創建文件,但是如何防止此警告消息出現在屏幕上?在a(追加)模式

+1

好吧,顯然你可以簡單地_test_如果文件存在。或者你可以「觸摸」它。 – arkascha

+1

'$ current =''; if(file_exists($ file)){$ current = file_get_contents($ file); }' –

+1

我不建議壓制錯誤/警告你可以使用'is_file'打開文件之前檢查文件是否存在,但是'$ current = @file_get_contents($ file);'應該禁止警告 –

回答

1

使用的fopen閱讀this

// opens file to load the current content 
if ($file = fopen('students.txt', 'a')){ 
    // add new content to file and writes content to file 
    fwrite($file ,$_POST["name"] . " : " . $_POST["grade"] . PHP_EOL); 
    // close file 
    fclose($file); 
    exit(0); 
} 
else { 
    echo "Cannot open file"; 
    exit(1); 
} 
0

使用FILE_APPEND選項file_put_contents()附加到文件,所以你不必先讀。它將根據需要創建文件。

$file = 'students.txt'; 
$current = $_POST["name"] . " : " . $_POST["grade"] . PHP_EOL; 
// writes content to file 
file_put_contents($file, $current, FILE_APPEND); 
相關問題