PHP 文件处理

fopen() 函数用于在 PHP 中打开文件。

打开文件

fopen() 函数用于在 PHP 中打开文件。

此函数的第一个参数含有要打开的文件的名称,第二个参数规定了使用哪种模式来打开文件:

<html>
<body>

<?php
$file=fopen("welcome.txt","r");
?>

</body>
</html>

关闭文件

fclose() 函数用于关闭打开的文件:

<?php
$file = fopen("test.txt","r");

//some code to be executed

fclose($file);
?>

检测 End-of-file

feof() 函数检测是否已到达文件末尾(EOF)。

在循环遍历未知长度的数据时,feof() 函数很有用。

注释:在 w 、a 和 x 模式下,您无法读取打开的文件!

if (feof($file)) echo "End of file";

逐行读取文件

fgets() 函数用于从文件中逐行读取文件。

注释:在调用该函数之后,文件指针会移动到下一行。

实例

下面的实例逐行读取文件,直到文件末尾为止:

<?php
$file = fopen("welcome.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while(!feof($file))
{
echo fgets($file). "<br>";
}
fclose($file);
?>

逐字符读取文件

fgetc() 函数用于从文件中逐字符地读取文件。

注释:在调用该函数之后,文件指针会移动到下一个字符。

实例

下面的实例逐字符地读取文件,直到文件末尾为止:

<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
while (!feof($file))
{
echo fgetc($file);
}
fclose($file);
?>

PHP Filesystem 参考手册

如需查看 PHP 文件系统函数的完整参考手册,请访问我们的PHP Filesystem 参考手册