For C/C++ programmers.
fscanf() does not work like C/C++, because PHP's fscanf() move file pointer the next line implicitly.
(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)
fscanf — 从文件中格式化输入
fscanf() 函数和 sscanf() 相似,但是它从与
stream
关联的文件中接受输入并根据指定的
format
来解释输入。
格式字符串中的任何空白会与输入流中的任何空白匹配。这意味着甚至格式字符串中的制表符(\t
)也会与输入流中的一个空格字符匹配。
每次调用 fscanf() 都会从文件中读取一行。
如果只给此函数传递了两个参数,解析后的值会被作为数组返回。否则,如果提供了可选参数,此函数将返回被赋值的数目。 可选参数必须用引用传递。
如果 format
中预期的子字符串超出 string
中有效的子字符串,则返回 null
。其它错误将返回 false
。
示例 #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);
?>
示例 #2 users.txt 的内容
javier argonaut pe hiroshi sculptor jp robert slacker us luigi florist it
For C/C++ programmers.
fscanf() does not work like C/C++, because PHP's fscanf() move file pointer the next line implicitly.
It would be great to precise in the fscanf documentation
that one call to the function, reads a complete line.
and not just the number of values defined in the format.
If a text file contains 2 lines each containing 4 integer values,
reading the file with 8 fscanf($fd,"%d",$v) doesnt run !
You have to make 2
fscanf($fd,"%d %d %d %d",$v1,$v2,$v3,$v4);
Then 1 fscanf per line.
If you want to read text files in csv format or the like(no matter what character the fields are separated with), you should use fgetcsv() instead. When a text for a field is blank, fscanf() may skip it and fill it with the next text, whereas fgetcsv() correctly regards it as a blank field.
Yet another function to read a file and return a record/string by a delimiter. It is very much like fgets() with the delimiter being an additional parameter. Works great across multiple lines.
function fgetd(&$rFile, $sDelim, $iBuffer=1024) {
$sRecord = '';
while(!feof($rFile)) {
$iPos = strpos($sRecord, $sDelim);
if ($iPos === false) {
$sRecord .= fread($rFile, $iBuffer);
} else {
fseek($rFile, 0-strlen($sRecord)+$iPos+strlen($sDelim), SEEK_CUR);
return substr($sRecord, 0, $iPos);
}
}
return false;
}
If you want to parse a cron file, you may use this pattern:
<?php
while ($cron = fscanf($fp, "%s %s %s %s %s %[^\n]s"))
{
}
?>
to include all type of visible chars you should try:
<?php fscanf($file_handler,"%[ -~]"); ?>
actually, instead of trying to think of every character that might be in your file, excluding the delimiter would be much easier.
for example, if your delimiter was a comma use:
%[^,]
instead of:
%[a-zA-Z0-9.| ... ]
Just make sure to use %[^,\n] on your last entry so you don't include the newline.