PHP 中经常需要对文件进行读取,有时候我们可能需要从指定的文件中读取一行信息,那么我们如何解决这一问题呢? PHP 内置了 fgets() 函数,可以从打开的文件中返回一行,本文就带大

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