PHP Create File and Write Data of Overwrite Write Additional Write Method Detailed Explanation

  • 2021-11-24 01:06:28
  • OfStack

This article describes the example of PHP to create files and write data (write overwrite, write append) method. Share it for your reference, as follows:

Here mainly introduces the PHP to create a file, and write data to the file, overwrite, additional implementation code, the need for friends can refer to the following:

To create a file, we use functions


fopen ( string filename, string mode )

Parameters:

filename: Create file name

mode: How to open the file filename

Where the list of mode possible values:

mode 说明
‘r' 只读方式打开,将文件指针指向文件头。
‘r+' 读写方式打开,将文件指针指向文件头。
‘w' 写入方式打开,将文件指针指向文件头并将文件大小截为零。如果文件不存在则尝试创建之。
‘w+' 读写方式打开,将文件指针指向文件头并将文件大小截为零。如果文件不存在则尝试创建之。
‘a' 写入方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。
‘a+' 读写方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。
‘x' 创建并以写入方式打开,将文件指针指向文件头。如果文件已存在,则 fopen() 调用失败并返回 FALSE,并生成1条 E_WARNING 级别的错误信息。如果文件不存在则尝试创建之。这和给 底层的 open(2) 系统调用指定 O_EXCL|O_CREAT 标记是等价的。此选项被 PHP 4.3.2 以及以后的版本所支持,仅能用于本地文件。
‘x+' 创建并以读写方式打开,将文件指针指向文件头。如果文件已存在,则 fopen() 调用失败并返回 FALSE,并生成1条 E_WARNING 级别的错误信息。如果文件不存在则尝试创建之。这和给 底层的 open(2) 系统调用指定 O_EXCL|O_CREAT 标记是等价的。此选项被 PHP 4.3.2 以及以后的版本所支持,仅能用于本地文件。

The following code is that I create a file named Demo and format txt by using the function fopen, and write "Welcome To ItCodeWorld! "The data.


<?php
// Two files to create 
$TxtFileName = "Demo.txt";
// Type the specified file as read-write, and create if the file is not saved 
if( ($TxtRes=fopen ($TxtFileName,"w+")) === FALSE){
echo(" Create a writable file: ".$TxtFileName." Failure ");
exit();
}
echo (" Create a writable file ".$TxtFileName." Success! </br>");
$StrConents = "Welcome To ItCodeWorld!";// To   What is written into the file 
if(!fwrite ($TxtRes,$StrConents)){ // Write information to a file 
echo (" Attempt to file ".$TxtFileName." Write ".$StrConents." Failure! ");
fclose($TxtRes);
exit();
}
echo (" Attempt to file ".$TxtFileName." Write ".$StrConents." Success! ");
fclose ($TxtRes); // Close the pointer 
?>

PHP Create File fopen ()

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

If you use the fopen() Open a file that does not exist. This function creates the file, assuming it is opened for write (w) or add (a).

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

Instances


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

PHP file permissions

If an error occurs when you try to run this code, check that you have access to the PHP file that writes information to your hard disk.

PHP writes to file fwrite ()

fwrite() Function is used to write to a file.

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

The following example writes the name to a new file called "newfile. txt":

Instances


<?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 a file, the string we send, $txt, contains "Bill Gates" for the first time and "Steve Jobs" for the second time. After the write 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 Coverage (Overwriting)

If "newfile. txt" now contains some data, we can show what happens when writing to an existing file. All existing data will be erased and started with a new file.

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

Instances


<?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 open this "newfile. txt" file now, both Bill and Steve disappear, leaving only the data we just wrote:

Mickey Mouse
Minnie Mouse

Line break '\ n' and carriage return '\ r'

As the name implies, the new line character is another 1 line, and the carriage return character is back to the beginning of the 1 line, so the carriage return character we usually write files should be exactly called the carriage return new line character

'\ n' 10 Wrap (newline)
'\ r' 13 Enter (return)

It can also be expressed as'\ x0a 'and'\ x0d '. (hexadecimal)

Under windows, the carriage return sign is "\ r\ n", but there is no "\ r" sign under Linux and other systems.

When parsing the contents of files in text or other formats, you often encounter a place where you decide to enter and break lines. At this time, you should pay attention to judging both "\ r\ n" and "\ n".

Write the program may get 1 line, trim it off '\ r', so you can get the string you need.

PHP file_put_contents () Function

The PHP file_put_contents () function is the best choice for writing a string to a file once or appending the contents of a string.

file_put_contents() The FALSE function is used to write a string to a file, returning the number of bytes of data written to the file on success or FALSE on failure.

Syntax:


int file_put_contents ( string filename, string data [, int flags [, resource context]] )

Parameter description:

参数 说明
filename 要写入数据的文件名
data 要写入的数据。类型可以是 string,array(但不能为多维数组),或者是 stream 资源
flags 可选,规定如何打开/写入文件。可能的值:
1. FILE_USE_INCLUDE_PATH:检查 filename 副本的内置路径
2. FILE_APPEND:在文件末尾以追加的方式写入数据
3. LOCK_EX:对文件上锁
context 可选,Context是1组选项,可以通过它修改文本属性

Examples:


<?php
echo file_put_contents("test.txt", "This is something.");
?>

Running this example, the browser outputs:

18

And test. txt file (under the same directory as the program) content is: This is something.

Prompt

If the file does not exist, create the file, which is equivalent to fopen() Function behavior.
If the file exists, the contents of the file will be emptied by default, and the flags parameter value can be set to FILE_APPEND to avoid it (see below).
This function can be safely used for binary objects.

Write content as append

When the flags parameter value is set to FILE_APPEND, it means that new data is written by appending content to the existing file content:


<?php
file_put_contents("test.txt", "This is another something.", FILE_APPEND);
?>

After executing the program, the contents of the test. txt file change to:

This is something.This is another something.

file_put_contents() The behavior of is actually equivalent to calling in turn fopen() , fwrite() As well as fclose() Function 1.

More readers interested in PHP can check the topics of this site: "php file operation summary", "PHP operation and operator usage summary", "PHP network programming skills summary", "PHP basic grammar introduction tutorial", "php object-oriented programming introduction tutorial", "php string (string) usage summary", "php+mysql database operation introduction tutorial" and "php common database operation skills summary"

I hope this article is helpful to everyone's PHP programming.


Related articles: