码迷,mamicode.com
首页 > 其他好文 > 详细

file_put_contents() ——将一个字符串写入文件

时间:2017-03-02 22:09:53      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:输出   div   als   and   echo   多维数组   hello   end   write   

语法:

int file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ]] )
参数描述
filename

必需。

要被写入数据的文件名。

规定要写入数据的文件。如果文件不存在,则创建一个新文件。

data

必需。规定要写入文件的数据。可以是字符串、数组或数据流。 stringarray 或者是 stream 资源

参数 data 可以是数组(但不能为多维数组),这就相当于 file_put_contents($filename, join(‘‘, $array))

flags

可选。

规定如何打开/写入文件。

flags 的值可以是 以下 flag 使用 OR (|) 运算符进行的组合

可能的值:

  • FILE_USE_INCLUDE_PATH:在 include 目录里搜索 filename。 更多信息可参见 include_path
  • FILE_APPEND:如果文件 filename 已经存在,追加数据而不是覆盖
  • LOCK_EX:在写入时获得一个独占锁
context

可选。

一个 context 资源。

规定文件句柄的环境。context 是一套可以修改流的行为的选项。

提示和注释

注释:请使用 FILE_APPEND 避免删除文件中已存在的内容。

该函数访问文件时,遵循以下规则:

  1. 如果设置了 FILE_USE_INCLUDE_PATH,那么将检查 *filename* 副本的内置路径
  2. 如果文件不存在,将创建一个文件
  3. 打开文件
  4. 如果设置了 LOCK_EX,那么将锁定文件
  5. 如果设置了 FILE_APPEND,那么将移至文件末尾。否则,将会清除文件的内容
  6. 向文件中写入数据
  7. 关闭文件并对所有文件解锁

如果成功,该函数将返回写入文件中的字符数。如果失败,则返回 False。

Warning

此函数可能返回布尔值 FALSE,但也可能返回等同于 FALSE 的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。

Note: 此函数可安全用于二进制对象。

例子:

 <?php
 echo file_put_contents("test.txt","Hello World. Testing!");
 ?> 

上面的代码将输出:

 21 

Example #1 Simple usage example

<?php
$file = ‘people.txt‘;
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= "John Smith\n";
// Write the contents back to the file
file_put_contents($file, $current);
?>

Example #2 Using flags

<?php
$file = ‘people.txt‘;
// The new person to add to the file
$person = "John Smith\n";
// Write the contents to the file, 
// using the FILE_APPEND flag to append the content to the end of the file
// and the LOCK_EX flag to prevent anyone else writing to the file at the same time
file_put_contents($file, $person, FILE_APPEND | LOCK_EX);
?>

 

http://php.net/manual/zh/function.file-put-contents.php

http://www.w3cschool.cn/php/func-filesystem-file-put-contents.html

 

file_put_contents() ——将一个字符串写入文件

标签:输出   div   als   and   echo   多维数组   hello   end   write   

原文地址:http://www.cnblogs.com/gengyi/p/6492605.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!