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