1、file_put_contents(PHP5+)
使用第三个参数 FILE_APPEND 进行追加
file_put_contents($file, $data);
//$data 可以是字符串、数字或数组(一维)。如果文件不存在,会主动创建。
写入格式化。换行符
\n
:Unix和Mac OS X;\r\n
:Windows。
PHP_EOL,表示当前操作系统的换行符
file_put_contents($file,$data . PHP_EOL, FILE_APPEND);
2、file_get_contents
3、打开文件
# $handle = fopen($filename,(模式)mode);
$handle = fopen($filename,'r');
模式 | 说明 |
---|---|
r | 只读;从文件起始位置开始读取 |
r+ | 读写 不存在则报错 |
w | 写入 如果文件不存在 则尝试创建 |
w+ | 写入并读 才可以用fread |
a | 追加写入 |
a+ | 读写方式 |
b | 都跟上二进制 |
3.1、使用fopen函数创建文件
$my_file = 'file.txt';//如果文件不存在(默认为当前目录下)
$handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file);
3.2、使用fopen函数打开文件
$my_file = 'file.txt';//假设文件file.txt存在
$handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file);
3.3、fopen函数结合fread读取文件
$my_file = 'file.txt';
$handle = fopen($my_file, 'r');
$data = fread($handle,filesize($my_file));
3.4、fopen函数结合fread读取文件
$my_file = 'file.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file);
$data = 'This is the data';
fwrite($handle, $data);
3.5、fopen函数结合fwrite函数向文件中追加内容
$my_file = 'file.txt';
$handle = fopen($my_file, 'a') or die('Cannot open file: '.$my_file);
$data = 'New data line 1';
fwrite($handle, $data);
$new_data = "\n".'New data line 2';
fwrite($handle, $new_data);
3.6、fopen() 函数还可用于打开互联网上的 URL 地址
$fh = fopen("http://www.baidu.com/", "r");
if($fh){
while(!feof($fh)) {
echo fgets($fh);
}
}
4、读取文件内容
fread(handle,字节)中文读和英文读
4、读取文件内容
fread(handle,字节)中文读和英文读
5、关闭文件句柄
fclose
6、当前指针所在位置
ftell
7、得到我们的指针
fseek
8、写内容
fwrite 从头开始写 fputs
9、指针重置
rewind
10、检测是否可写
is_writable