PHP 文件操作


PHP提供了十分便利的文件操作函数,如file_put_contents()函数能直接把字符串写入文件,而不需要手动打开和关闭文件。

将文件内容读入一个字符串


file_get_contents ( string $filename , bool $use_include_path = false , 
        resource $context = null , int $offset = -1 , int $maxlen = ? ) : string
<?php
// 无需手动打开和关闭文件
$content = file_get_contents('/tmp/learn_php.txt');
var_dump($content);    输出string(48) "PHP提供了十分便利的文件操作函数。"

注意:应避免文件大小超出内存大小。

将一个字符串写入文件


file_put_contents ( string $filename , mixed $data , int $flags = 0 , resource $context = ? ) : int
<?php
// 写文件就是这么便利
$content = '今天是个学PHP的好日子。';
file_put_contents('./learn_php.txt', $content);

打开文件


fopen ( string $filename , string $mode , bool $use_include_path = false , resource $context = ? ) : resource

fopen() 将 filename 绑定到一个流上。

<?php

// 以只读方式打开文件
$fp = fopen('./learn_php.txt', 'r');

// 以读写方式打开文件
$fp = fopen('./learn_php.txt', 'r+');

// 以写入方式打开文件,并将文件置空,如果文件不存在将会新建
$fp = fopen('./learn_php.txt', 'w');

// 以读写方式打开文件,并将文件置空,如果文件不存在将会新建
$fp = fopen('./learn_php.txt', 'w+');

// 以追加方式打开文件,并将指针指向文件末尾,如果文件不存在将会新建
$fp = fopen('./learn_php.txt', 'a');

// 以读取追加方式打开文件,并将指针指向文件末尾,如果文件不存在将会新建
$fp = fopen('./learn_php.txt', 'a+');

关闭文件


fclose ( resource $handle ) : bool

关闭 handle 指向的文件。

<?php
$fp = fopen('./learn_php.txt', 'r');

// 做一些文件操作

fclose($fp);

读取文件


fread ( resource $handle , int $length ) : string

fread() 从文件指针 handle 读取最多 length 个字节。

<?php
// 获取文件内容并赋值给一个字符串
$filename = "./learn_php.txt";
$fp = fopen($filename, "r");
$contents = fread($fp, filesize($filename));
fclose($fp);

写入文件


fwrite ( resource $handle , string $string , int $length = ? ) : int

fwrite() 把 string 的内容写入 文件指针 handle 处。

<?php
$fp = fopen('./learn_php.txt', 'w');
fwrite($fp, '学习PHP');
fclose($fp);

更多操作可参考PHP文件操作手册。