如何在php中创建新文件。我正在尝试使用fopen功能。但据我所知,只有当文件已经存在时,这才有效。我对很感兴趣
- 打开文件(如果存在)
- 如果不存在,请创建一个新的文本文件
- 读取和写入文件
fopen()
将打开一个不存在的文件,如果您将模式标志传递给它:
fopen("myfile.txt", "w"); //places the pointer at 0 and overwrites any existing data or creates new
fopen("myfile.txt", "w+"); //opens for writing and reading
file_put_contents()
函数将数据转储到一个文件中:
$data = "my data block";
$myFile = "myFile.txt";
file_put_contents($myFile, $data);
从文档来看:file_put_contents()
的可能参数是:
filename
写入数据的文件的路径。
data
要写入的数据。可以是字符串、数组或流资源。如果数据是流资源,则该流的剩余缓冲区将为复制到指定的文件。这与使用类似stream_copy_to_stream()。也可以将数据参数指定为一维数组。这相当于file_put_contents($filename,内爆('',$array))。
flags
标志可以是以下标志的任意组合,并与二进制OR(|)运算符。
要检查文件是否存在,请使用file_exists()
函数和fopen()
或file_get_contents()
(如果您想将现有数据吸入变量中):
if(file_exists($myFile))
{
fopen($myFile);
//do something
} else {
//use file_put_contents or fopen to dump file
}