Home > Backend Development > PHP Tutorial > PHP uses fopen and file_get_contents to read file instances

PHP uses fopen and file_get_contents to read file instances

WBOY
Release: 2016-07-29 09:00:36
Original
1164 people have browsed it

To read files in PHP, you can use the two functions fopen and file_get_contents. There is no essential difference between the two, except that the PHP code for reading files in the former is a little more complicated than the latter. This article explains the implementation code of fopen and file_get_contents to read files through examples. Coders who need it can refer to it.

The code for fopen to read files is as follows:

<?<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>?>       
Copy after login

Note that fopen needs to use the fgets and fclose functions to read files.

file_get_contents The code for reading files is as follows:

<?<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>?>       
Copy after login

This function reads all the file contents at once and displays them, but if the file is too large, PHP will occupy a lot of memory.

Of course, there are also methods like file, which generally read files into arrays. At the same time, files can also be read

The above introduces the example of using fopen and file_get_contents to read files in PHP, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

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