fscanf()
fscanf() — Parses input from a file according to a format.
Built-in function of PHP 8.5. The manual lists it as available in PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.
What it does
The function fscanf() is similar to sscanf(), but it takes its input from a file associated with stream and interprets the input according to the specified format.
Signature
fscanf(resource $stream, string $format, mixed &...$vars): array|int|false|null
Parameters
| Parameter | Type | What it takes |
|---|---|---|
| $stream | resource | A file system pointer resource that is typically created using fopen(). |
| $format | string | The interpreted format for string, which is described in the documentation for sprintf() with following differences: Function is not locale-aware. F, g, G and b are not supported. D stands for decimal number. i stands for integer with base detection. n stands for number of characters processed so far. s stops reading at any whitespace character. * instead of argnum$ suppresses the assignment of this conversion ... |
| &...$vars | mixed | The optional assigned values. |
Return value
If only two parameters were passed to this function, the values parsed will be returned as an array. Otherwise, if optional parameters are passed, the function will return the number of assigned values. The optional parameters must be passed by reference. If there are more substrings expected in the format than there are available within string, null will be returned. On other errors, false will be returned. When optional parameters are used and the end of the input read from stream is reached before any value has been parsed, -1 is returned.
Example
A runnable snippet:
$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);
See also
fread(), fgets(), sscanf(), printf(), sprintf()
All PHP 8.5 built-in functions
Reference card built from the PHP manual page fscanf() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.