在php中写文件有几种,一种是利用fopen与fwirte函数实现,另一种是利用file_put_contents实现读写,下面我来介绍它们用法。
方法一,利用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 可选。规定要写入的最大字节数。
例
代码如下 | 复制代码 |
/** |
方法二,利用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=>写文件的时候先锁定,防止多人同时写入造成内容丢失

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version
Useful JavaScript development tools
