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

PHP uses fopen and file_get_contents to read file instances, _PHP tutorial

WBOY
WBOYOriginal
2016-07-12 08:58:04867browse

php uses fopen and file_get_contents to read file instances.

You can use the two functions fopen and file_get_contents to read files in php. There is no essential difference between the two, except for the former. The php code for reading files is a bit 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>?>       

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

The code for file_get_contents to read the file 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>?>       

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

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

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1105551.htmlTechArticlephp uses fopen and file_get_contents to read file instances. 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 former reads text...
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