zoukankan      html  css  js  c++  java
  • PHP fwrite() 函数与 file_put_contents() 函数的比较

    两个 PHP 函数都可以把字符串保存到文件中,fwrite() 函数的格式是:

    int fwrite ( resource handle , string string [ , int length] )

    它只能写入字符串

    file_put_contents() 函数的格式是:

    int file_put_contents ( string $filename, mixed $data [, int $flags [, resource $context]] )

    其中 file 是文件路径,data 可以是字符串,可以是一维数组或二维数组,不能是多维数组

    两种方法当要写入的文件不存在时,都会自动创建文件。当文件存在时, 根据使用 fwrite() 函数之前使用 fopen() 函数打开文件资源的模式,或者使用 file_put_contents() 函数的第三个参数来确定写入文件的模式:

    例如

    使用 fopen() , fwrite() , fclose() 这一系列函数时

    <?php
    
    $filename = "data.txt";
    
    $handle = fopen($filename,"w") or die("打开".$filename."文件失败");
    
    $str = "updating your profile with your name";
    
    fwrite($handle,$str);
    
    fclose($handle);

    就相当于 file_put_contents() 的

    <?php
    
    $filename = "data.txt";
    
    $str = "updating your profile with your name";
    
    file_put_contents($filename,$str);

    将原本需要 3 行代码的地方简化到了 1 行。

    当需要追加写入文件时,fopen() , fwrite() , fclose() 的

    <?php
    
    $filename = "data.txt";
    
    $handle = fopen($filename,"a") or die("打开".$filename."文件失败");
    
    $str = "updating your profile with your name";
    
    fwrite($handle,$str);
    
    fclose($handle);

    就相当于 file_put_contents() 的

    <?php
    
    $filename = "data.txt";
    
    $str = "updating your profile with your name";
    
    file_put_contents($filename,$str,FILE_APPEND);

    另外为了避免多人同时操作文件,可以增加文件的锁声明:

    file_put_contents($filename,$str,FILE_APPEND|LOCK_EX);

    效率:file_put_contents() 函数与依次调用 fopen() , fwrite() , fclose() 的功能一样,也就是说,file_put_contents() 在写入每条数据时,都要打开和关闭资源,而使用 fopen()、 fwrite() 、fclose() 时,只需要一次打开资源和一次关闭资源关闭,效率上使用 fopen()、 fwrite() 、fclose() 更快,适用于处理大量数据;如果处理的数据量不多,为了代码简洁可以使用file_put_contents() 函数。

  • 相关阅读:
    合并二叉树
    剑指 Offer 68
    剑指 Offer 42. 连续子数组的最大和
    C语言 递归实现迷宫寻路问题
    C语言数据结构 统计英文文字每个“单词”出现次数
    C语言 双链表的频度排序管理
    C语言 插入排序使链表递增
    c语言 简单的天数计算器
    数据结构 链表的头插法逆置
    C语言 删除指定的单词
  • 原文地址:https://www.cnblogs.com/dee0912/p/4055428.html
Copyright © 2011-2022 走看看