fscanf()
The fscanf() function is a built-in PHP function that reads data from a file according to a specified format. This function is used to read formatted data from
What is the fscanf() Function?
The fscanf() function reads from an open file and parses its contents according to a printf-style format string. Instead of giving you a raw line of text the way fgets() does, fscanf() splits the input into typed fields — strings, integers, floats — in a single step. It is PHP's tool of choice when a file follows a fixed, column-based layout and you want each value already converted to the right type.
This page covers the syntax, the format specifiers you can use, the two ways fscanf() can return its results, the most common gotchas, and how it compares to related functions.
Syntax
fscanf(resource $stream, string $format, mixed &...$vars): array|int|false| Parameter | Description |
|---|---|
$stream | A file pointer returned by fopen(). |
$format | A format string built from specifiers such as %s, %d, and %f. |
&...$vars | Optional. One or more variables passed by reference to receive the parsed fields. |
Return value depends on how you call it:
- With extra variable arguments → returns the number of fields successfully assigned, or
falseat end of file. - Without extra variables → returns an array of the parsed fields instead of writing to variables.
fscanf() advances the file pointer past whatever it consumed, so repeated calls walk through the file token by token.
Format Specifiers
The format string is the heart of fscanf(). The most common specifiers are:
| Specifier | Reads |
|---|---|
%s | A string (stops at the next whitespace) |
%d | A signed decimal integer |
%f | A floating-point number |
%c | A single character |
%x | A hexadecimal integer |
%% | A literal % character |
Whitespace in the format string matches any run of whitespace (spaces, tabs, newlines) in the input, which is why %s is whitespace-delimited rather than line-delimited.
Reading a File With Variables
The typical pattern is: open the file, loop while fscanf() keeps returning the expected field count, then close it. Suppose data.txt contains one record per line:
John Smith 30 50000.5
Jane Doe 28 62000You can parse each line into typed variables like this:
<?php
$file = fopen('data.txt', 'r');
if ($file === false) {
die("Error: Could not open file.");
}
while (fscanf($file, "%s %s %d %f", $first, $last, $age, $salary) === 4) {
echo "Name: $first $last, Age: $age, Salary: $salary\n";
}
fclose($file);
?>Output:
Name: John Smith, Age: 30, Salary: 50000.5
Name: Jane Doe, Age: 28, Salary: 62000Comparing the return value against 4 (the number of fields the format expects) is the key to a safe loop: at end of file fscanf() returns false, and on a malformed line it returns a smaller count, so the loop stops cleanly instead of spinning forever.
Reading a File Into an Array
If you omit the variable arguments, fscanf() returns each parsed record as an array. This is handy when you want to collect rows rather than process them one variable at a time:
<?php
$file = fopen('data.txt', 'r');
while ($row = fscanf($file, "%s %s %d %f")) {
// $row is [first, last, age, salary]
[$first, $last, $age, $salary] = $row;
echo "$last, $first earns $salary\n";
}
fclose($file);
?>Output:
Smith, John earns 50000.5
Doe, Jane earns 62000fscanf() vs. sscanf()
fscanf() reads from a file pointer; sscanf() does exactly the same parsing but on a string you already have in memory. If your data is in a variable rather than a file, reach for sscanf():
<?php
$count = sscanf("2024-06-21", "%d-%d-%d", $year, $month, $day);
echo "$count fields parsed: $year / $month / $day\n";
?>Output:
3 fields parsed: 2024 / 6 / 21Common Gotchas
%sstops at whitespace, not at the line end. A name likeNew Yorkis read as two%sfields, not one. Match the real shape of your data.- Always check the return value. Looping on the field count (
=== 4) — not on!feof()— keeps you safe from incomplete lines and infinite loops. - Verify
fopen()first.fscanf()needs a valid resource; a failed open returnsfalse. - For comma-separated data, prefer
fgetcsv().fscanf()is built for whitespace-delimited, fixed-format columns, not quoted CSV fields.
Related Functions
sscanf()— parse a formatted string instead of a file.fgetcsv()— read and split CSV lines.fgets()— read a raw line of text.fopen()/fclose()— open and close the file stream.
Conclusion
fscanf() turns whitespace-delimited file content into typed PHP values in a single call. Pick the variable form when you process records one at a time, or the array form when you collect them. Always validate the return value to drive your loop, and switch to sscanf() for in-memory strings or fgetcsv() for true CSV.