Home >Backend Development >PHP Problem >How to read the file content in php and convert it to an array
In PHP, we can use the file operation function to read the file content and convert it into an array.
The following are some commonly used file operation functions:
fopen()
: Open a file pointerfgets()
: Read a line from the open file pointer feof()
: Check whether the file pointer has reached the end of the file fclose()
: Close the file pointer Our goal is to convert the file contents into an array, where each line is an element of the array.
The code is implemented as follows:
<?php $file = fopen("data.txt", "r"); $data = array(); while(!feof($file)) { $line = fgets($file); $line = trim($line); if(!empty($line)) { $data[] = $line; } } fclose($file); print_r($data); ?>
This code first opens a file pointer through fopen()
, pointing to a file named data.txt
file, and use r
mode to indicate read-only mode.
Next, use a while
loop to read each line from the file pointer and use the trim()
function to remove spaces and newlines at the end of the line. If the row is not empty, it is added to the array $data
.
Finally, use the fclose()
function to close the file pointer.
You can replace data.txt
with the file name and path you want to read. The file being read must exist on the server, and PHP must have read permission.
Summary
In PHP, we can use file operation functions to read the file content and convert it into an array. This is a very useful skill, especially useful when writing web applications. Remember, pay attention to file paths and permissions when reading files.
The above is the detailed content of How to read the file content in php and convert it to an array. For more information, please follow other related articles on the PHP Chinese website!