php读取文件内容的体式格局有许多,这里为人人引见几个经常使用的读取文件的函数。
第一种:
<?php $file_path = "test.txt"; if(file_exists($file_path)){ $fp = fopen($file_path,"r"); $str = fread($fp,filesize($file_path));//指定读取大小,这里把全部文件内容读取出来 echo $str = str_replace("\r\n","<br />",$str); }
剖析:fopen()函数翻开一个文件或URL。
第二种:
<?php $file_path = "test.txt"; if(file_exists($file_path)){ $str = file_get_contents($file_path);//将全部文件内容读入到一个字符串中 $str = str_replace("\r\n","<br />",$str); echo $str; } ?>
剖析:file_get_contents()函数把全部文件读入一个字符串中。
第三种:
<?php $file_path = "test.txt"; if(file_exists($file_path)){ $fp = fopen($file_path,"r"); $str = ""; $buffer = 1024;//每次读取 1024 字节 while(!feof($fp)){//轮回读取,直至读取完全部文件 $str .= fread($fp,$buffer); } $str = str_replace("\r\n","<br />",$str); echo $str; } ?>
剖析:fread()函数读取最大字节数;feof()函数搜检是不是已抵达文件末端。
第四种:
<?php $file_path = "test.txt"; if(file_exists($file_path)){ $file_arr = file($file_path); for($i=0;$i<count($file_arr);$i++){//逐行读取文件内容 echo $file_arr[$i]."<br />"; } /* foreach($file_arr as $value){ echo $value."<br />"; }*/ } ?>
剖析:file()函数把全部文件读入一个数组。
第五种:
<?php $file_path = "test.txt"; if(file_exists($file_path)){ $fp = fopen($file_path,"r"); $str =""; while(!feof($fp)){ $str .= fgets($fp);//逐行读取。假如fgets不写length参数,默许是读取1k。 } $str = str_replace("\r\n","<br />",$str); echo $str; } ?>
剖析:fgets()函数从翻开的文件中返回一行。
以上引见了几种读取文件内容的函数,仅供人人参考。
更多相干题目请接见ki4网:PHP视频教程
以上就是php读取文件内容的要领和函数有哪些?的细致内容,更多请关注ki4网别的相干文章!