php 逐行读取文本文件

在读取文本时,我们要注意一个事情,那就是换行符,应为我们在写文档时会手动换行,这个换行符需不需要保存就要看自己的需求了。

这里封装了两个方法,一个保留换行,一个不保留。$path为文件路径+文件名 

1.不保留换行 

 1 function read($path){
 2     $file = fopen($path, "r");
 3     $user=array();
 4     $i=0;
 5 //输出文本中所有的行,直到文件结束为止。
 6     while(! feof($file))
 7     {
 8         $user[$i]= trim(fgets($file));//fgets()函数从文件指针中读取一行
 9         $i++;
10     }
11     fclose($file);
12     $user=array_filter($user);
13     return $user;
14 }
不保留换行读取文件

2.保留换行

 1 function read($path){
 2     $file = fopen($path, "r");
 3     $user=array();
 4     $i=0;
 5 //输出文本中所有的行,直到文件结束为止。
 6     while(! feof($file))
 7     {
 8         $user[$i]= fgets($file);//fgets()函数从文件指针中读取一行
 9         $i++;
10     }
11     fclose($file);
12     $user=array_filter($user);
13     return $user;
14 }
保留换行读取文件

猜你喜欢

转载自www.cnblogs.com/paopao123/p/10598906.html