Get the App
SLTechnology News&Howtos  ›  Development  › 

How does PHP read data from txt files

Shulou Source: shulou.com Published: 2022-06-01 11:12:45 10月04日 Update

This article mainly introduces PHP how to read data from the txt file, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let Xiaobian take you to understand.

I. Open / close files

1. When operating on a file, you must first open the file. Use the fopen () function to open the file. The syntax is as follows:

Fopen (filename,mode,include_path,context)

2. After the operation on the file, you should close the file and use the function fclose ()

For example:

Read and write the file 1. Read the whole file

There are three functions that can be used: the readfile () function, the file () function, and the file_get_contents () function.

The readfile () function, which reads a file and writes it to the output buffer, and returns false if an error occurs.

The file () function stores the contents of the file in an array by line, including newline characters, and returns false if it fails.

The file_get_contents () function reads the contents of the file into a string, and if there are offset and maxlen parameters, it starts reading the content of length maxlen at the location specified by the parameter offset, and returns false if it fails.

Example:

The running result is shown in the figure:

2. Read a row of data

Both the fgets () function and the fgetss () function read a row of data.

Fgets () function:

String fgets (resource $handle [, int $length])

$handle is the open file, and $length is the length of the data to be read.

Fgetss () function:

String fgetss (resource $handle [, int $length [, string $allowable_tags]])

The fgetss () function is a variant of the fgets () function, the same as fgets (), except that the fgetss () function removes any HTML and PHP tags from the read text.

3. Read a character

When searching and replacing a character, you need to read it pertinently. Use the function: fgetc ()

4. Read a string of any length

Read the specified length of data from the file, using the function fread ()

Thank you for reading this article carefully. I hope the article "PHP how to read data from txt files" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Tags: Function file data character article length content line parameter string same three value location interest variant just at the same time instance newline character Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Apple Huawei NVidia MariaDB