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());

 

转载于:https://www.cnblogs.com/huay/p/10368767.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值