文件创建 – PHP 高级

文件创建 – PHP 高级

创建文件 – fopen( )
fopen( ) 函数也用于创建文件。在 PHP 中,通过相同的函数打开文件,也使用相同的函数创建文件。当您在不存在的文件上使用 fopen( ) 函数时,假设打开文件进行追加(a)或写入(w),它会创建新文件。
$myfile = fopen("example2.txt", "w")
//This will create a new file naming "example2" on same directory where the code resides.
写入文件 -fwrite( )
它用于写入文件。这里,fwrite()的第一个参数包含要写入的文件的名称,第二个参数是要写入的字符串。
<?php
 $file = fopen("ex2.txt", "w") or die("Unable to open file!");
 $text = "Code\n";
 fwrite($file, $text);
 $text = "Projects\n";
 fwrite($file, $text);
 fclose($file);
 ?>
//这将创建一个包含字符串 $text 的文本文件,其中包含“Code”和“Projects”
覆盖:
现在“ex2.txt”包含一些数据,我们可以显示当我们打开现有文件进行写入时会发生什么。所有现有数据都将被删除,我们从一个空文件开始。
<?php
 $file = fopen("ex2.txt", "w") or die("Unable to open file!");
 $text = "Projects\n";
 fwrite($file, $text);
 $text = "Tutorial and More\n";
 fwrite($file, $text);
 fclose($file);
 ?>
//现在当我们运行代码时,以前的数据将被删除并被新数据替换。

猜你喜欢

转载自blog.csdn.net/qq_37270421/article/details/133357138
今日推荐