zoukankan      html  css  js  c++  java
  • 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, "
    ");
    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("
    ", '', 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());
  • 相关阅读:
    索引器
    异常
    C#各版本
    构造函数
    值类型和引用类型
    面向对象聊天机器人
    linux 系统快捷键
    linux 系统常用设置
    linux 系统介绍
    linux 命令学习.txt
  • 原文地址:https://www.cnblogs.com/huay/p/10368767.html
Copyright © 2011-2022 走看看