fgets() 函数从文件指针中读取一行。
语法
fgets(file,length)
参数描述
file 必需。规定要读取的文件。
length 可选。规定要读取的字节数。默认是 1024 字节。
说明
从 file 指向的文件中读取一行并返回长度最多为 length - 1 字节的字符串。碰到换行符(包括在返回值中)、eof 或者已经读取了 length - 1 字节后停止(要看先碰到那一种情况)。如果没有指定 length,则默认为 1k,或者说 1024 字节。
若失败,则返回 false。
提示和注释
注释:length 参数从 php 4.2.0 起成为可选项,如果忽略,则行的长度被假定为 1024 字节。从 php 4.3 开始,忽略掉 length将继续从流中读取数据直到行结束。如果文件中的大多数行都大于 8 kb,则在脚本中指定最大行的长度在利用资源上更为有效。
注释:从 php 4.3 开始本函数可以安全用于二进制文件。早期的版本则不行。
注释:如果碰到 php 在读取文件时不能识别 macintosh 文件的行结束符,可以激活 auto_detect_line_endings 运行时配置选项。
下面使用php fgets()函数按行读取文本文件的实例,代码如下
$handle = @fopen("d:/public/test.txt", "r");
if ($handle) {
while (!feof($handle)) {
$str = fgets($handle, 4096);
//$str = '#主单词1#';
if(preg_match('/#(.+)#/',$str,$matches)){
$di_word = $matches[1];
$di_word = mysql_escape_string($di_word);
$sql = " select di_id from `du_index` where di_word = '{$di_word}'";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
$di_id = $row[0];
if (count($dy_word)>0){
$sql = " insert into `du_yun` (`di_id`,`di_word`,`dy_word`,`dy_description`,`dy_status`,`dy_time`) values";
for ($i=0;$i<count($dy_word);$i++){
$sql .= " ('{$di_id_1}','{$di_word_1}','{$dy_word[$i]}','{$dy_description[$i]}','1',now()),";
}
$result = mysql_query(substr($sql,0,-1).';');
if ($result){}else{
echo $sql . '<br />';
}
}
$di_id_1 = $di_id;
$di_word_1 = $di_word;
$dy_word = $dy_description = array();
$sql = '';
continue;
};
//$str = '[志願者]參[與]人員';
if (preg_match('/^\[(.+)\](.+)$/',$str,$matches)){
$dy_word[] = trim($matches[1]);
$dy_description[] = trim($matches[2]);
continue;
}
}
if (count(dy_word)>0){
$sql = " insert into `du_yun` (`di_id`,`di_word`,`dy_word`,`dy_description`,`dy_status`,`dy_time`) values";
for ($i=0;$i<count($dy_word);$i++){
$sql .= " ('{$di_id_1}','{$di_word_1}','{$dy_word[$i]}','{$dy_description[$i]}','1',now()),";
}
$result = mysql_query(substr($sql,0,-1).';') or die(mysql_error());
if ($result){}else{
echo $sql . '<br />';
}
}
fclose($handle);
}
以上就是php fgets() 函数使用实例代码的详细内容。