PHP基础 专题
您的位置:php > PHP基础 专题 > PHP读取文件
PHP读取文件
作者:--    发布时间:2019-11-20

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

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册