Home > Backend Development > PHP Tutorial > php 使用fopen与file_get_contents读取文件范例

php 使用fopen与file_get_contents读取文件范例

WBOY
Release: 2016-06-13 12:28:48
Original
781 people have browsed it

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

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

fopen读取文件的代码如下:

<span style="color: #000000;">php</span><span style="color: #800080;">$file_name</span> = "1.txt"<span style="color: #000000;">;</span><span style="color: #0000ff;">echo</span> <span style="color: #800080;">$file_name</span> . ""<span style="color: #000000;">;</span><span style="color: #800080;">$fp</span> = <span style="color: #008080;">fopen</span>(<span style="color: #800080;">$file_name</span>, 'r'<span style="color: #000000;">);</span><span style="color: #008000;">//</span><span style="color: #008000;">$buffer=fgets($fp);</span><span style="color: #0000ff;">while</span> (!<span style="color: #008080;">feof</span>(<span style="color: #800080;">$fp</span><span style="color: #000000;">)) {    </span><span style="color: #800080;">$buffer</span> = <span style="color: #008080;">fgets</span>(<span style="color: #800080;">$fp</span><span style="color: #000000;">);    </span><span style="color: #0000ff;">echo</span> <span style="color: #800080;">$buffer</span><span style="color: #000000;">;}</span><span style="color: #008080;">fclose</span>(<span style="color: #800080;">$fp</span><span style="color: #000000;">);</span>?>       
Copy after login

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

 

file_get_contents读取文件的代码如下:

<span style="color: #000000;">php</span><span style="color: #0000ff;">if</span> (<span style="color: #008080;">file_exists</span>(<span style="color: #800080;">$path</span><span style="color: #000000;">)) {    </span><span style="color: #800080;">$body</span> = <span style="color: #008080;">file_get_contents</span>(<span style="color: #800080;">$path</span><span style="color: #000000;">);    </span><span style="color: #0000ff;">echo</span> <span style="color: #800080;">$body</span>; <span style="color: #008000;">//</span><span style="color: #008000;">输入文件内容</span><span style="color: #000000;">    } </span><span style="color: #0000ff;">else</span><span style="color: #000000;"> {    </span><span style="color: #0000ff;">echo</span> "文件不存在 <span style="color: #800080;">$path</span>"<span style="color: #000000;">;}</span>?>       
Copy after login

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

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template