PHP没有警告创建新文件:“没有这样的文件”
问题描述:
我想创建通过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
(追加)模式
答
使用的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);
}
答
使用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);
好吧,显然你可以简单地_test_如果文件存在。或者你可以“触摸”它。 – arkascha
'$ current =''; if(file_exists($ file)){$ current = file_get_contents($ file); }' –
我不建议压制错误/警告你可以使用'is_file'打开文件之前检查文件是否存在,但是'$ current = @file_get_contents($ file);'应该禁止警告 –