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>?>
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>?>
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.