Home  >  Article  >  php教程  >  php 使用fopen与file_get_contents读取文件实例,

php 使用fopen与file_get_contents读取文件实例,

WBOY
WBOYOriginal
2016-06-13 08:45:151521browse

php 使用fopen与file_get_contents读取文件实例,

php中读取文件可以使用fopen和file_get_contents这两个函数,二者之间没有本质区别,只是前者读取文件的php代码相比后者要复杂一点。本文章通过实例向大家讲解fopen和file_get_contents读取文件的实现代码。需要的码农可以参考一下。

fopen读取文件的代码如下:

<?<span>php
</span><span>$file_name</span> = "1.txt"<span>;
</span><span>echo</span> <span>$file_name</span> . "
"<span>;
</span><span>$fp</span> = <span>fopen</span>(<span>$file_name</span>, 'r'<span>);
</span><span>//</span><span>$buffer=fgets($fp);</span>
<span>while</span> (!<span>feof</span>(<span>$fp</span><span>)) {
    </span><span>$buffer</span> = <span>fgets</span>(<span>$fp</span><span>);
    </span><span>echo</span> <span>$buffer</span><span>;
}
</span><span>fclose</span>(<span>$fp</span><span>);
</span>?>       

注意fopen读取文件需要配合使用fgets和fclose函数。

 

file_get_contents读取文件的代码如下:

<?<span>php
</span><span>if</span> (<span>file_exists</span>(<span>$path</span><span>)) {
    </span><span>$body</span> = <span>file_get_contents</span>(<span>$path</span><span>);
    </span><span>echo</span> <span>$body</span>; <span>//</span><span>输入文件内容</span>
<span>    
} </span><span>else</span><span> {
    </span><span>echo</span> "文件不存在 <span>$path</span>"<span>;
}
</span>?>       

这个函数是一次性读取所有文件内容并显示出来,但是如果文件超大会导致php占很大的内存了。

当然还有像file这种一般是把文件读成数组了,同时也可以实现读取文件了

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