PHP读取文件

PHP提供了从文件读取数据的各种功能(函数)。 可使用不同的函数来读取所有文件数据,逐行读取数据和字符读取数据。

下面给出了可用的几种PHP文件读取函数。

  • fread()
  • fgets()
  • fgetc()

PHP读取文件 - fread()

PHP fread()函数用于读取文件的数据。 它需要两个参数:文件资源($handle)和文件大小($length)。

语法

string fread (resource $handle , int $length )

$handle表示由fopen()函数创建的文件指针。
$length表示要读取的字节长度。

示例

<?php    
$filename = "c:\\file1.txt";    
$fp = fopen($filename, "r");//open file in read mode    

$contents = fread($fp, filesize($filename));//read file    

echo "<pre>$contents</pre>";//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 ] )

示例

<?php    
$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 )

示例

<?php    
$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

上一篇: PHP打开文件 下一篇: PHP写入文件