PHP在没有警告的情况下创建新文件:";“没有此类文件”;

PHP在没有警告的情况下创建新文件:";“没有此类文件”;,php,file,warnings,Php,File,Warnings,我想通过php创建一个新的.txt文件,如下所示: $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; // wri

我想通过php创建一个新的.txt文件,如下所示:

    $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在这种情况下创建了文件,但如何防止此警告消息出现在屏幕上?

读取模式下使用fopen


使用
FILE\u APPEND
选项将
FILE\u put\u contents()。如有必要,它将创建该文件

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

显然,您可以简单地测试文件是否存在。或者您可以触摸它。
$current='';如果(file_exists($file)){$current=file_get_contents($file);}
我不建议抑制错误/警告您可以在打开文件之前轻松检查文件是否存在,使用
is_file
但是“$current=@file_get_contents($file);”应该禁止警告哦当然。。。非常感谢。
$file = 'students.txt';
$current = $_POST["name"] . " : " . $_POST["grade"] . PHP_EOL;
// writes content to file
file_put_contents($file, $current, FILE_APPEND);