PHP file creation/writing

PHP Create File - fopen()

The fopen() function is also used to create files. It may be a little confusing, but in PHP, the same function used to create a file is to open it.

If you open a file with fopen() that does not exist, this function creates the file, assuming the file was opened for writing (w) or incrementing (a).

The following example creates a new file named "testfile.txt". This file will be created in the same directory as the PHP code:

Example

$myfile = fopen("testfile.txt", "w")

PHP file permissions

If an error occurs when you try to run this code, please check that you have PHP file access to write information to disk.

PHP write file - fwrite()

The fwrite() function is used to write to a file.

The first argument to fwrite() contains the filename of the file to be written, and the second argument is the string to be written.

The following example writes names to a new file named "newfile.txt":

Example

<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "Bill Gates\n";
fwrite($myfile, $txt);
$txt = "Steve Jobs\n";
fwrite($myfile, $txt);
fclose($myfile);
?>

Note that we wrote to the file "newfile.txt" twice. Every time we write to the file, the string $txt we send contains "Bill Gates" the first time and "Steve Jobs" the second time. After writing is complete, we use the fclose() function to close the file.

If we open the "newfile.txt" file, it should look like this:

Bill Gates
Steve Jobs

PHP Overwriting

If "newfile.txt" now contains some data, we can show what happens when the existing file is written. All existing data will be erased and a new file will start.

In the following example, we open an existing file "newfile.txt" and write some new data to it:

Example

<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "Mickey Mouse\n";
fwrite($myfile, $txt);
$txt = "Minnie Mouse\n";
fwrite($myfile, $txt);
fclose($myfile);
?>

If we now open this "newfile.txt" file, both Bill and Steve are gone, leaving only the data we just wrote:

Mickey Mouse
Minnie Mouse

PHP add (add)

If you want to keep adding but not overwriting the file, use the following format
<?php
$myfile = fopen("newfile.txt", "a");
$txt = "Mickey Mouse\n";
fwrite($myfile, $txt);
$txt = "Minnie Mouse\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
Use "a", which means adding to add, and only add operations when operating files.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326847586&siteId=291194637