1. readfile() 函数
readfile() 函数读取文件,并把它写入输出缓冲。
//读取一个名为text.txt的文件
<?php
echo readfile("text.txt");
?>
2.fopen()函数
打开文件的更好的方法是通过 fopen() 函数。此函数为您提供比 readfile() 函数更多的选项。fopen() 的第一个参数包含被打开的文件名,第二个参数规定打开文件的模式,打开文件的模式如下表所示:
3.fread()函数
fread() 函数读取打开的文件。fread() 的第一个参数包含待读取文件的文件名,第二个参数规定待读取的最大字节数。如下 PHP 代码把 "web.txt" 文件读至结尾:
fread($myfile,filesize("web.txt"));
4.fclose()函数,关闭文件
fclose() 函数用于关闭打开的文件。<?php
$myfile = fopen("web.txt", "r");
fclose($myfile);
?>
注释:用完文件后把它们全部关闭是一个良好的编程习惯。您并不想打开的文件占用您的服务器资源。
当不存在所要打开的文件时,使用or die 警告信息
<?php
$myfile = fopen("web.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("web.txt"));
fclose($myfile);
?>
4.fgets()函数,读取单行文件
fgets() 函数用于从文件读取单行。
<?php
$myfile = fopen("web.txt", "r") or die ("Unable to open file!");
echo fgets($myfile);//只读取一行,<span style="font-family: Verdana, Arial, 宋体; line-height: 18px; background-color: rgb(249, 249, 249);">调用 fgets() 函数之后,文件指针会移动到下一行。</span>
fclose($myfile);
?>
5.-feof()函数,检查 End-Of-File
feof() 函数检查是否已到达 "end-of-file" (EOF)。feof() 对于遍历未知长度的数据很有用。
下例逐行读取 "web.txt" 文件,直到 end-of-file:
<?php
$myfile = fopen("web.txt", "r") or die("Unable to open file!");
// 输出单行直到 end-of-file
while(!feof($myfile))
{
echo fgets($myfile) ."<br>";
}
fclose($myfile);
?>
6.fgetc()函数,读取单字符
fgetc() 函数用于从文件中读取单个字符。下例逐字符读取 "web.txt" 文件,直到 end-of-file:
<?php
$myfile = fopen("web.txt", "r") or die("Unable to open file!");
// 输出单字符直到 end-of-file
while(!feof($myfile))
{
echo fgetc($myfile);//<span style="font-family: Verdana, Arial, 宋体; line-height: 18px; background-color: rgb(249, 249, 249);">在调用 fgetc() 函数之后,文件指针会移动到下一个字符</span>
}
fclose($myfile);
?>