
PHP中经常需要对文件进行读取,有时候我们可能需要从指定的文件中读取一行信息,那么我们如何解决这一问题呢?PHP内置了fgets()函数,可以从打开的文件中返回一行,本文就带大家一起来看一看。
首先需要了解的是语法:
fgets ( resource $handle , int $length = ? )
-
$handle:文件指针必须是有效的,必须指向由
fopen()或fsockopen()成功打开的文件(并还未由fclose()关闭)。 -
$length:从 $handle指向的文件中读取一行并返回长度最多为 $length – 1 字节的字符串。碰到换行符(包括在返回值中)、
EOF或者已经读取了$length - 1字节后停止(看先碰到那一种情况)。如果没有指定$length,则默认为 1K,或者说 1024 字节。 -
返回值:从指针
$handle指向的文件中读取了$length - 1字节后返回字符串。如果文件指针中没有更多的数据了则返回false。错误发生时返回false。
代码实例:
带读取文件信息:
//exit.txt php good better Knowledge is power 我有一件小法宝 PHP is the best language for web programming, but what about other languages?
1.只有一个参数$handle
<?php
$resource=fopen("./exit.txt","r");
echo fgets($resource)."<br>";
echo fgets($resource)."<br>";
echo fgets($resource)."<br>";
输出: php good better Knowledge is power 我有一件小法宝 PHP is the best language for web programming, but what about other languages?
2.有两个参数$handle、$length
<?php
$resource=fopen("./exit.txt","r");
echo fgets($resource,10)."<br>";
echo fgets($resource,10)."<br>";
echo fgets($resource,10)."<br>";
输出:php good
better Kn
owledge i
推荐:《2021年PHP面试题大汇总(收藏)》《php视频教程》
以上就是PHP中fgets()函数的详解的详细内容,更多请关注php中文网其它相关文章!

声明:本文原创发布php中文网,转载请注明出处,感谢您的尊重!如有疑问,请联系admin@php.cn处理
- 上一篇:详解PHP中的explode()函数
- 下一篇:没有了