PHP教程
PHP Mysql
PHP面向对象
PHP常用

PHP 读取文件

PHP 读取文件

PHP 提供了多种从文件读取数据的函数。有不同的函数可以让您读取所有文件数据、逐行读取数据和逐字符读取数据。
下面给出了可用的 PHP 文件读取函数。
fread() fgets() fgetc()

PHP 读取文件-fread()

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

语法

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
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4