如果文件不存在,是否可以只用 PHP 编写文件?
$file = fopen("test.txt","w");
echo fwrite($file,"Some Code Here");
fclose($file);
因此,如果文件确实存在,则代码不会编写代码,但如果文件不存在,它将创建一个新文件并编写代码
提前致谢!
您可以使用fopen()
模式 ofx
而不是w
,如果文件已经存在,这将使 fopen 失败。与 using 相比,这样检查的优点file_exists
是,如果在检查是否存在和实际打开文件之间创建文件,它不会出现错误。缺点是如果文件已经存在,它(有点奇怪)会生成一个 E_WARNING 。
换句话说(在@ThiefMaster 下面的评论的帮助下),类似的东西;
$file = @fopen("test.txt","x");
if($file)
{
echo fwrite($file,"Some Code Here");
fclose($file);
}
如果文件存在,请在执行代码之前检查 file_exists($filename)。
if (!file_exists("test.txt")) {
$file = fopen("test.txt","w");
echo fwrite($file,"Some Code Here");
fclose($file);
}
创建了一个名为 $file 的变量。此变量包含我们要创建的文件的名称。
使用 PHP 的 is_file 函数,我们检查文件是否已经存在。
如果 is_file 返回一个布尔 FALSE 值,那么我们的文件名不存在。
如果文件不存在,我们使用函数 file_put_contents 创建文件。
//The name of the file that we want to create if it doesn't exist.
$file = 'test.txt';
//Use the function is_file to check if the file already exists or not.
if(!is_file($file)){
//Some simple example content.
$contents = 'This is a test!';
//Save our content to the file.
file_put_contents($file, $contents);
}