虽然有很多相关文章,但我还是喜欢自己记录下来,方便查阅。
打开文件
fopen() 函数用于在 PHP 中打开文件。
// 无法打开,返回0 (false)
fopen() 函数用于在 PHP 中打开文件。
关闭文件
fclose() 函数用于关闭打开的文件
<?php
$file = fopen("test.txt","r");
//执行一些代码
fclose($file);
?>
检测文件末尾(EOF)
if (feof($file)) echo “文件结尾”;
逐行读取文件
fgets()函数用于从文件中逐行读取文件
注释:在调用该函数之后,文件指针会移动到下一行。
<?php
$file = fopen("welcome.txt", "r") or exit("无法打开文件!");
while(!feof($file))
{
echo fgets($file). "<br>";
}
fclose($file);
?>
逐字符读取文件
fgetc() 函数用于从文件中逐字符地读取文件。
<?php
$file=fopen("welcome.txt","r") or exit("无法打开文件!");
while (!feof($file))
{
echo fgetc($file);
}
fclose($file);
?>