fscanf

 

 

fscanf

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

fscanf — 从文件中格式化输入

说明

mixed fscanf ( resource $handle , string $format [, mixed &$... ] )

fscanf() 函数和 sscanf() 相似,但是它从与 handle 关联的文件中接受输入并根据指定的 format(定义于 sprintf()的文档中)来解释输入。

格式字符串中的任何空白会与输入流中的任何空白匹配。这意味着甚至格式字符串中的制表符 \t 也会与输入流中的一个空格字符匹配。

每次调用 fscanf() 都会从文件中读取一行。

参数

 

handle

文件系统指针,是典型地由 fopen() 创建的 resource(资源)。

format

参数格式是 sprintf() 文档中所描述的格式。

...

The optional assigned values.

返回值

如果只给此函数传递了两个参数,解析后的值会被作为数组返回。否则,如果提供了可选参数,此函数将返回被赋值的数目。 可选参数必须用引用传递。

更新日志

 

版本说明
4.3.0 在 PHP 4.3.0 之前,从文件中读入的最大字符数是 512(或者第一个 \n,看先碰到哪种情况)。从 PHP 4.3.0 起可以读取任意长的行。

范例

 

Example #1 fscanf() 例子

<?php
$handle = fopen("users.txt", "r");
while ($userinfo = fscanf($handle, "%s\t%s\t%s\n")) {
    list ($name, $profession, $countrycode) = $userinfo;
    //... do something with the values
}
fclose($handle);
?>

 

Example #2 users.txt 的内容

javier  argonaut        pe
hiroshi sculptor        jp
robert  slacker us
luigi   florist it

参见

 

 

<?php

    $handle=fopen("../good/html/1.txt","r");

    while($kcinfo=fscanf($handle, "%s\t%s\t%s\n"))        //读取文件中数据并格式化

    {

        list($kch,$kcm,$xf)=$kcinfo;                    //将返回数组中的值赋给变量

        echo $kch."&nbsp".$kcm."&nbsp".$xf."<br/>";    //输出数据

    }

    fclose($handle);

?>

 

 

 

posted @ 2017-02-21 10:10  feiyun8616  阅读(226)  评论(0编辑  收藏  举报