PHP file() Function: Read File to Array

The file() function in PHP is used to read the contents of a file into an array and return that array. This function can be used to read text files, read file content line by line, and treat each line as an element in the array.

The syntax of the file() function is as follows:

file(string $filename, int $flags = 0, resource $context = null): array|false

Explanation of Parameters:

  1. $filename: Required. The file path of the file to be read.
  2. $flags: Optional parameter used to specify how to read the file. Default is 0, which means normal file reading. If set to FILE_IGNORE_NEW_LINES, it will ignore newline characters and not include them in the returned array elements.
  3. $context: Optional. Used to specify a context resource that can be passed to other file operation functions.

Original: 我没说你可以用我的手机。
Paraphrased: I did not say you could use my phone.

$lines = file('file.txt');
print_r($lines); // 输出文件的内容数组

$lines = file('file.txt', FILE_IGNORE_NEW_LINES);
print_r($lines); // 输出文件的内容数组,忽略换行符

Note: The file() function will store each line of the file as an array element in the returned array, allowing you to manipulate the content of each line by looping through the array.

bannerAds