文件读写 #

一、读取文件 #

1.1 file_get_contents() #

php
<?php
$content = file_get_contents('data.txt');
echo $content;

1.2 file() #

php
<?php
$lines = file('data.txt');
foreach ($lines as $line) {
    echo $line;
}

1.3 fopen/fread/fclose #

php
<?php
$handle = fopen('data.txt', 'r');
$content = fread($handle, filesize('data.txt'));
fclose($handle);

1.4 fgets() #

php
<?php
$handle = fopen('data.txt', 'r');
while (($line = fgets($handle)) !== false) {
    echo $line;
}
fclose($handle);

二、写入文件 #

2.1 file_put_contents() #

php
<?php
file_put_contents('data.txt', 'Hello World');
file_put_contents('data.txt', 'More data', FILE_APPEND);

2.2 fwrite() #

php
<?php
$handle = fopen('data.txt', 'w');
fwrite($handle, "Hello World\n");
fclose($handle);

三、文件模式 #

模式 说明
r 只读
r+ 读写
w 写入(清空)
w+ 读写(清空)
a 追加
a+ 读写追加
x 创建写入

四、文件检查 #

php
<?php
if (file_exists('data.txt')) {
    echo "文件存在";
}

if (is_readable('data.txt')) {
    echo "可读";
}

if (is_writable('data.txt')) {
    echo "可写";
}

五、总结 #

本章学习了文件读写的基本操作,下一章将学习文件上传。

最后更新:2026-03-26