php数组的逐行写入文件与读取
1 <?php 2 3 /** 4 * 5 * 对数组$arr1=['Apple Orange Banana Strawberry'] 写入文件,并读取 6 **/ 7 class IoFile 8 { 9 private $path; 10 11 public function __construct($paths) 12 { 13 $this->path = $paths; 14 } 15 16 //写入 17 public function inter($arr) 18 { 19 if (!is_array($arr) && !empty($arr)) { 20 return '数组异常'; 21 } 22 23 $file = fopen($this->path, 'w'); 24 if (!$file) { 25 return '文件打开失败'; 26 } 27 foreach ($arr as $k => $v) { 28 fwrite($file, $v); 29 if ($v != end($arr)) { 30 fwrite($file, "\r\n"); 31 } 32 } 33 fclose($file); 34 } 35 36 //读取 37 public function outer() 38 { 39 $arr = []; 40 if (!file_exists($this->path)) { 41 return "文件不存在!"; 42 } 43 $file = fopen($this->path, 'r'); 44 if (!$file) { 45 return '文件打开失败'; 46 } 47 while (!feof($file)) { 48 $arr[] = str_replace("\r\n", '', fgets($file)); 49 } 50 fclose($file); 51 return $arr; 52 } 53 } 54 55 $arr1 = ['Apple', 'Orange', 'Banana', 'Strawberry']; 56 $path = 'tt.txt'; 57 $obj = new IoFile($path); 58 echo $obj->inter($arr1); 59 60 echo '<hr/>'; 61 var_dump($obj->outer());