Home  >  Article  >  Backend Development  >  How to read the file content in php and convert it to an array

How to read the file content in php and convert it to an array

PHPz
PHPzOriginal
2023-04-18 09:47:49716browse

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 pointer
  • fgets() : 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn