PHP文件操作(二)-文件的读取

1.fread()    //读取打开的文件

fread(file,length)

file:必选项,规定要读取的打开的文件

length:必选项,规定要读取的最大字节数。

<?php
	$files = fopen("1.txt","r") or die("文件打开失败");
	$text = fread($files,1024);
	fclose($files);
     echo $text; ?>

 2.file_get_contents()  //把一个文件内容读入到一个字符串中

<?php
	echo file_get_contents("1.txt");
?>

 3.fgets()  //从打开的文件中返回一行

fgets(file,length)

file:必选项。规定要读取的文件。

length:可选项。规定要读取的字节数。默认是 1024 字节。

fgets()一次最多从打开的文件资源中读取一行内容

<?php
	$file = fopen("2.txt","r") or die("文件打开失败");
	while(!feof($file)){  //feof()函数判断一个文件指针是否位于文件的结束处,如果在文件末尾处,则返回TRUE
		$text = fgets($file,2048);
		echo $text."<br>";
	}
	fclose($file);
?>

 4.fgetc()  //只读取当前指针位置处的一个字符。如果遇到文件结束标志EOF将返回FALSE

<?php
	$file = fopen("2.txt","r") or die("文件打开失败");
	while(false != ($text = fgetc($file))){   //在文件中每次循环读取一个字符
		echo $text."<br>";   //输出单个字符
	}
	fclose($file);
?>

 5.file()    //把整个文件读入到一个数组中。数组中的每个元素对应文件中相应的行

<?php
	print_r(file("2.txt")); //输出:Array ( [0] => test [1] => test1 [2] => test2 [3] => test3 [4] => test4 ) 
?>

 6.readfile()   //读取整个文件,立即输出到输出缓冲区,并返回读取的字节数

<?php
	readfile("2.txt");  //输出:test test1 test2 test3 test4
?>
原文地址:https://www.cnblogs.com/sch01ar/p/7764167.html