Home > php教程 > PHP源码 > body text

php中写文件函数实例程序

WBOY
Release: 2016-06-08 17:23:35
Original
1087 people have browsed it

在php中写文件有几种,一种是利用fopen与fwirte函数实现,另一种是利用file_put_contents实现读写,下面我来介绍它们用法。

<script>ec(2);</script>

方法一,利用fopen与fwirte函数实现

1,PHP如何打开文件

使用PHP函数fopen()打开一个文件,fopen()一般使用2个参数表示打开文件的路径和文件模式。比如:

 代码如下 复制代码
$fp=fopen("../cnbruce.txt",'w');

 

其中 "../cnbruce.txt" 就表示打开的cnbruce.txt文件的路径(相对当前执行程序文件的路径),'w'表示以只写的方式打开该文本文件。

写文件用


fwrite(file,string,length)

参数说明:

file 必需。规定要写入的打开文件。

string 必需。规定要写入文件的字符串。

length 可选。规定要写入的最大字节数。


 代码如下 复制代码

/**
 * 写文件函数
 *
 * @param string $filename 文件名
 * @param string $text 要写入的文本字符串
 * @param string $openmod 文本写入模式('w':覆盖重写,'a':文本追加)
 * @return boolean
 */
function write_file($filename, $text, $openmod = 'w') {
 if (@$fp = fopen($filename, $openmod)) {
  flock($fp, 2);
  fwrite($fp, $text);
  fclose($fp);
  return true;
 } else {
  return false;
 }
}

方法二,利用file_put_contents实现读写

file_put_contents函数有个参数LOCK_EX非常有用,加上它之后,再也没有出现过内容缺失的情况了。

这个参数LOCK_EX的意思很直白,就是写文件时,先锁上这个文件,这样只允许某个客户端访问的时候写,其他客户端访问不能写了。

我的用法如下:

 代码如下 复制代码

file_put_contents($file, $content, FILE_APPEND|LOCK_EX)

解释:

$file=>这个是写入文件的路径+文件名
$content=>这个是写入文件的内容
FILE_APPEND=>直接在该文件已有的内容后面追加内容
LOCK_EX=>写文件的时候先锁定,防止多人同时写入造成内容丢失 

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!