Home > Article > Backend Development > Let’s talk about how PHP reads data from txt files
This article mainly introduces you to the relevant knowledge about PHP. It mainly introduces to you the relevant information about how PHP reads data from txt files. The article introduces it through example codes and pictures. It is very detailed and has certain reference value for everyone to learn or use PHP. I hope it will be helpful to everyone.
(Recommended tutorial: PHP video tutorial)
1. Right When operating a file, you must first open the file. Use the fopen() function to open the file. The syntax is:
fopen(filename, mode, include_path, context);
2. After the file operation is completed, the file should be closed, using the function fclose();
For example:
There are three functions that can be used, namely: readfile() function, file() function, file_get_contents() function.
readfile() function is used to read a file and write it to the output buffer. If an error occurs, it returns false.
The file() function stores the file contents into an array line by line, including newlines, and returns false if it fails.
The file_get_contents() function reads the file content into a string. If there are offset and maxlen parameters, the content with a length of maxlen will be read starting from the position specified by the offset parameter. If it fails, false will be returned.
Example:
The running result is as shown in the figure:
The fgets() function and the fgetss() function both read one line of data.
fgets() function:
string fgets ( resource $handle [, int $length ] );
$handle is the opened file , $length is the length of data to be read.
fgetss() function:
string fgetss ( resource $handle [, int $length [, string $allowable_tags ]] );
fgetss The () function is a variant of the fgets() function, which is the same as fgets(), except that the fgetss() function removes any HTML and PHP tags from the read text.
When searching and replacing a certain character, you need to read a certain character in a targeted manner. Use the function: fgetc();
To read data of a specified length from a file, use the function fread();
(Recommended tutorial: PHP video tutorial)
The above is the detailed content of Let’s talk about how PHP reads data from txt files. For more information, please follow other related articles on the PHP Chinese website!