php 使用fopen与file_get_contents读取文件实例,
php 使用fopen与file_get_contents读取文件实例,
php中读取文件可以使用fopen和file_get_contents这两个函数,二者之间没有本质区别,只是前者读取文件的php代码相比后者要复杂一点。本文章通过实例向大家讲解fopen和file_get_contents读取文件的实现代码。需要的码农可以参考一下。
fopen读取文件的代码如下:
<?<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>?>
注意fopen读取文件需要配合使用fgets和fclose函数。
file_get_contents读取文件的代码如下:
<?<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>?>
这个函数是一次性读取所有文件内容并显示出来,但是如果文件超大会导致php占很大的内存了。
当然还有像file这种一般是把文件读成数组了,同时也可以实现读取文件了

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1
Easy-to-use and free code editor

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
