Use fscanf() when you need to reads formatted values from an open stream using scanf-style placeholders in a PHP application. The examples below show the actual operation and its limitations.
What Is fscanf() in PHP?
Reads formatted values from an open stream using scanf-style placeholders. The exact signature supported by your installation depends on its PHP version and enabled extensions.
Its syntax is:
fscanf($stream, string $format, mixed &...$vars = ...): array|int|false|null
Parameters and return value: The parameter types, optional arguments, references, and return type are shown in the signature above. Optional parameters are marked with an ellipsis in this reference signature.
Example 1: Basic Usage
<?php
$stream = fopen("php://temp","w+"); fwrite($stream,"Alex 32
"); rewind($stream); print_r(fscanf($stream,"%s %d")); fclose($stream);
Output:
Array
(
[0] => Alex
[1] => 32
)
Example 2: Different Input or Behavior
<?php
$stream = fopen("php://temp","w+"); fwrite($stream,"12.5 8
"); rewind($stream); print_r(fscanf($stream,"%f %d")); fclose($stream);
Output:
Array
(
[0] => 12.5
[1] => 8
)
Practical Example: Applying the Function
<?php
$stream = fopen("php://temp","w+"); fwrite($stream,"apple,4
pear,7
"); rewind($stream); while (($record = fscanf($stream,"%[^,],%d")) !== false) { if ($record[0] !== null) echo $record[0] . ":" . $record[1] . PHP_EOL; } fclose($stream);
Output:
apple:4
pear:7
Important Behavior and Edge Cases
The input must match the expected format; use fgetcsv() for real CSV with quoting rules.
Comparison With Related Functions
| Approach | Difference |
|---|---|
fscanf() | Reads formatted values from an open stream using scanf-style placeholders. |
| Related operation | sscanf() parses an existing string; fscanf() reads an open stream. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Ignoring the function-specific limitation | The input must match the expected format; use fgetcsv() for real CSV with quoting rules. |
| Confusing this function with a related operation | sscanf() parses an existing string; fscanf() reads an open stream. |
Key Takeaways
- Reads formatted values from an open stream using scanf-style placeholders.
- The input must match the expected format; use fgetcsv() for real CSV with quoting rules.
- sscanf() parses an existing string; fscanf() reads an open stream.
Use fscanf() for the specific operation demonstrated above. Check its prerequisites and handle failure conditions before using it with production data.