Home > Article > Backend Development > Use the PHP function "file" to read the file contents and return an array
Use the PHP function "file" to read the file content and return the array
In PHP, there are many convenient functions that can help us handle file operations. Among them, the function "file" is a very commonly used function. It can read the contents of a file and convert it into an array and return it.
The function prototype is as follows:
array file ( string $filename [, int $flags = 0 [, resource $context ]] )
Let’s introduce in detail how to use the "file" function.
First, we need a file to test this function. We create a text file called "sample.txt" and write a few lines of text into it.
The content of the sample.txt file is as follows:
Hello, world! This is a sample file. It is used for testing file functions in PHP.
Next, we can use the "file" function to read this file and store the results in an array.
$fileContent = file("sample.txt"); print_r($fileContent);
When we execute this code, the result is as follows:
Array ( [0] => Hello, world! [1] => This is a sample file. [2] => It is used for testing file functions in PHP. )
As you can see, the function "file" successfully converts the file content into an array and treats each line of text as an array of an element.
It is worth noting that the function "file" will also retain the newline character (
) at the end of each line in the file in the array element by default. If we don't want to preserve these newlines, we can use the "FILE_IGNORE_NEW_LINES" parameter.
$fileContent = file("sample.txt", FILE_IGNORE_NEW_LINES); print_r($fileContent);
At this time, the printed result is:
Array ( [0] => Hello, world! [1] => This is a sample file. [2] => It is used for testing file functions in PHP. )
You can see that the newline character has been removed from the array elements.
In addition, we can also specify other options through the "flags" parameter. For example, we can use the "FILE_SKIP_EMPTY_LINES" parameter to skip empty lines in the file.
$fileContent = file("sample.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); print_r($fileContent);
At this time, the printed result is:
Array ( [0] => Hello, world! [1] => This is a sample file. [2] => It is used for testing file functions in PHP. )
You can see that all blank lines are skipped, and only non-blank lines are saved in the array.
To summarize, PHP's "file" function provides us with a very convenient way to read the contents of a file and convert it into an array. We can control whether to retain newlines and skip empty lines through parameters, allowing us to process file operations more flexibly according to needs.
The above is the detailed content of Use the PHP function "file" to read the file contents and return an array. For more information, please follow other related articles on the PHP Chinese website!