本文概述
PHP提供了各種功能來從文件讀取數據。有多種功能允許你讀取所有文件數據, 逐行讀取數據以及逐字符讀取數據。
下面提供了可用的PHP文件讀取功能。
fread()
fgets()
fgetc()
PHP讀取文件-fread()
PHP fread()函數用于讀取文件的數據。它需要兩個參數:文件資源和文件大小。
句法
string fread (resource $handle , int $length )
$ handle表示由fopen()函數創建的文件指針。
$ length表示要讀取的字節長度。
例子
$filename = "c:\file1.txt";
$fp = fopen($filename, "r");//open file in read mode
$contents = fread($fp, filesize($filename));//read file
echo "
$contents";//printing data of file
fclose($fp);//close file
?>
輸出
this is first line
this is another line
this is third line
PHP讀取文件-fgets()
PHP fgets()函數用于從文件讀取單行。
句法
string fgets ( resource $handle [, int $length ] )
例子
$fp = fopen("c:\file1.txt", "r");//open file in read mode
echo fgets($fp);
fclose($fp);
?>
輸出
this is first line
PHP讀取文件-fgetc()
PHP fgetc()函數用于從文件讀取單個字符。要使用fgetc()函數獲取所有數據, 請在while循環內使用!feof()函數。
句法
string fgetc ( resource $handle )
例子
$fp = fopen("c:\file1.txt", "r");//open file in read mode
while(!feof($fp)) {
echo fgetc($fp);
}
fclose($fp);
?>
輸出
this is first line this is another line this is third line