Home > Article > Backend Development > Instructions for using fopen function to open, create and read PHP files_PHP tutorial
This article introduces a simple file operation function fopen. The fopen function can open, read, and assist in file saving. Let me summarize the operation of PHP files.
Open file
The simplest syntax of fopen is as follows:
fopen(filepath,mode)
Here is an example of PHP code to open a file:
The code is as follows | Copy code | ||||
$f = fopen("c:datainfo.txt", "r"); ?>
|
Describes how to use PHP built-in function fclose to close a file.
The fclose function syntax is as follows:
fclose(filepointer)
代码如下 | 复制代码 |
$f = fopen("c:datainfo.txt", "r"); |
If successful, the fclose function returns TRUE, if failed, the fclose function returns FALSE.
Here is a PHP code example of the fclose function:
The code is as follows | Copy code |
$f = fopen("c:datainfo.txt", "r"); fclose($f); ?>
|
代码如下 | 复制代码 |
|
$f= fopen("C:blablaphpwrite.txt","w");
代码如下 | 复制代码 |
$f= fopen("C:blablaphpwrite.txt","a"); |
The code is as follows | Copy code |
The code is as follows | Copy code |
$f= fopen("C:blablaphpwrite.txt","a"); |
For the parameter mode value of the fopen function, see fopen for details.
The fwrite function returns the number of bytes written to the file. If an error occurs, it returns FALSE.
fgets reads a line of file
Use the PHP built-in function fgets to read a line of a file.
The syntax for fgets to read a line of file content is:
fgets(filepointer)
Let’s give an example below to describe how to read a file line by line.
Suppose we have a sites.txt file with three lines and the following content:
woyouxian.comblabla.cngoogle.com
The file path of sites.txt is:
C:blablaphpsites.txt
We use PHP to read the file content line by line. The PHP code is as follows:
代码如下 | 复制代码 |
Execute the PHP file and the displayed result returned is:
site: woyouxian.comsite: blabla.cnsite: google.com
The first line of this PHP code opens a file, and the last line closes a file. The while loop statement means that when the file does not end, read one line and execute it in a loop until the file pointer reaches the end of the article.
The feof function is a built-in function of PHP, used to test whether the file pointer has reached the end of the file. Returns TRUE if yes, FALSE if not. The English meaning of eof is end of file, which is easy to remember.
Under normal circumstances, the return value of the fgets function is a string. If an error occurs, it returns FALSE