Home  >  Article  >  php教程  >  php读取文件内容几种正确方法

php读取文件内容几种正确方法

WBOY
WBOYOriginal
2016-06-08 17:27:08983browse
<script>ec(2);</script>

//方法一 用while来些fgets一行行读
$file_name="1.txt";

 代码如下 复制代码

$fp=fopen($file_name,'r');

 while(!feof($fp))
 {
  $buffer=fgets($fp,4096);
  echo $buffer."
";
 }
 fclose($fp);


 
// 方法二 用file一次保存到数组再用foreach输出

 代码如下 复制代码
$array = file( $file );
foreach( $array as $v =>$_v )
{
  echo $_v,'
';
}


//方法三用file_get_contents一次读出

 代码如下 复制代码
if( is_file( $file_name ) )
{
 $cn = file_get_contents( $file_name );
 echo $cn;
}


/*
相关函数参考地址
fopen http://www.111cn.net/phper/18/d5da4dcc30303f7684a91dec184e24fc.htm
feof 是否到文件末
fgets http://www.111cn.net/phper/21/php-fgets.htm
fclose 关闭
file http://www.111cn.net/phper/24/f5d9e092cfa826b89c45b339bdd3dd4f.htm
file_get_contents http://www.111cn.net/phper/24/f8d52eaae81ea27383375ead36ffbd4d.htm
foreach http://www.111cn.net/phper/18/foreach-foreach.htm
*/

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn