Content · Programming · PHP

PHP fscanf() Function: Usage and Examples

Understand PHP fscanf() with three examples, return behavior, important pitfalls, and related operations.

1 views Published Oct 16, 2026 Updated Oct 16, 2026

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

ApproachDifference
fscanf()Reads formatted values from an open stream using scanf-style placeholders.
Related operationsscanf() parses an existing string; fscanf() reads an open stream.

Common Beginner Mistakes

MistakeCorrect Approach
Ignoring the function-specific limitationThe input must match the expected format; use fgetcsv() for real CSV with quoting rules.
Confusing this function with a related operationsscanf() 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.

Share this resourceSend this page to someone who may find it useful.