PHP 8.3.4 Released!

fscanf

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

fscanfInterpretiert den Input einer Datei entsprechend einem angegebenen Format

Beschreibung

fscanf(resource $stream, string $format, mixed &...$vars): array|int|false|null

Die Funktion fscanf() ist ähnlich zu sscanf(), wobei sie ihren Input aus der mit stream angegebenen Datei liest, und entsprechend dem angegebenen format interpretiert.

Beliebige Whitespace-Zeichen (z. B. Leerzeichen, Tabulator etc.) im Format String gelten mit beliebigen Whitespace-Zeichen des Input-Streams als übereinstimmend. Das heißt, dass auch ein Tabulator (\t) im Formatstring mit einem einzigen Leerzeichen im Input-Stream als übereinstimmend gelten kann.

Jeder fscanf()-Aufruf liest eine Zeile aus der Datei aus.

Parameter-Liste

stream

Eine Dateisystemressource (resource), wie sie in der Regel von fopen() zurückgegeben wird.

format

Das interpretierte Format für string, wie es in der Dokumentation zu sprintf() beschrieben ist, mit den folgenden Unterschieden:

  • Die Funktion beachtet die Locale nicht.
  • F, g, G und b werden nicht unterstützt.
  • D steht für eine Dezimalzahl.
  • i steht für eine Ganzzahl mit Angabe der Basis.
  • n steht für die Anzahl der bisher verarbeiteten Zeichen.
  • s beendet das Lesen beim ersten Whitespace-Zeichen.
  • * anstelle von argnum$ unterdrückt die Zuweisung dieser Umwandlungsspezifikation.

vars

Die optional zugewiesenen Werte.

Rückgabewerte

Wenn nur zwei Parameter an die Funktion übergeben wurden, werden die geparseten Werte in einem Array zurückgegeben. Andernfalls gibt die Funktion die Anzahl der zugewiesenen Werte zurück. Die optionalen Parameter müssen per Referenz übergeben werden.

Wenn im format mehr Teilstrings erwartet werden, als in string verfügbar sind, wird null zurückgegeben. Bei anderen Fehlern wird false zurückgegeben.

Beispiele

Beispiel #1 fscanf()-Beispiel

<?php
$handle
= fopen("users.txt", "r");
while (
$userinfo = fscanf($handle, "%s\t%s\t%s\n")) {
list (
$name, $profession, $countrycode) = $userinfo;
// Tue etwas mit den Werten ...
}
fclose($handle);
?>

Beispiel #2 Inhalt der Datei users.txt

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

Siehe auch

  • fread() - Liest Binärdaten aus einer Datei
  • fgets() - Liest die Zeile von der Position des Dateizeigers
  • fgetss() - Liest eine Zeile von der Position des Dateizeigers und entfernt HTML Tags.
  • sscanf() - Überträgt einen String in ein angegebenes Format
  • printf() - Liefert einen formatierten String
  • sprintf() - Gibt einen formatierten String zurück

add a note

User Contributed Notes 10 notes

up
18
yasuo_ohgaki at hotmail dot com
23 years ago
For C/C++ programmers.

fscanf() does not work like C/C++, because PHP's fscanf() move file pointer the next line implicitly.
up
7
Bertrand dot Lecun at prism dot uvsq dot Fr
16 years ago
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.
up
2
eugene at pro-access dot com
22 years ago
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.
up
1
worldwideroach at hotmail dot com
18 years ago
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;
}
up
-1
nico at nicoswd dot com
10 years ago
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"))
{

}

?>
up
-2
loco.xxx at gmail dot com
17 years ago
to include all type of visible chars you should try:

<?php fscanf($file_handler,"%[ -~]"); ?>
up
-3
robert at NOSPAM dot NOSPAM
21 years ago
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.
up
-8
arentzen at religion dot dk
16 years ago
If you want fscanf()to scan one variable in a large number of lines, e.g an Ipadress in a line with more variables, then use fscanf with explode()
<?
$filename = "somefile.txt";
$fp = fopen($filename, "r") or die ("Error opening file! \n");
$u = explode(" ",$line); // $u is the variable eg. an IPadress
while ($line = fscanf($fp,"%s",$u)) {
if(preg_match("/^$u/",$_SERVER['REMOTE_ADDR'])) {$badipadresss++;} // do something and continue scan
}
?>
Besides, fscanf()is much faster than fgets()
up
-6
james at zephyr-works dot com
22 years ago
fscanf works a little retardedly I've found. Instead of using just a plain %s you probably will need to use sets instead. Because it works so screwy compared to C/C++, fscanf does not have the ability to scan ahead in a string and pattern match correctly, so a seemingly perfect function call like:

fscanf($fh, "%s::%s");

With a file like:

user::password

Will not work. When fscanf looks for a string, it will look and stop at nothing except for a whitespace so :: and everything except whitespace is considered part of that string, however you can make it a little smarter by:

fscanf($fh, "%[a-zA-Z0-9,. ]::%[a-zA-Z0-9,. ]" $var1, $var2);

Which tells it that it can only accept a through z A through Z 0 through 9 a comma a period and a whitespace as input to the string, everything else cause it to stop taking in as input and continue parsing the line. This is very useful if you want to get a sentence into the string and you're not sure of exactly how many words to add, etc.
up
-24
hdh265 at 163 dot com
8 years ago
The use of PHP code in the ACM submission
Here is a sample solution for problem 1001 using PHP:
<?php
while (fscanf(STDIN, "%d%d", $a, $b) == 2) {
print (
$a + $b) . "\n";
}
To Top