Skip to content

fscanf()

What is the fscanf() Function?

The fscanf() function is a built-in PHP function that reads data from a file according to a specified format. It modifies the provided variables by reference and returns the number of fields successfully read, or false on error.

Here's the basic syntax of the fscanf() function:

The PHP syntax of fscanf()

php
fscanf(file, format, ...);

Where file is the file pointer to read from, format is a string specifying the format of the data to read, and ... represents one or more variables to store the data read.

How to Use the fscanf() Function?

Using the fscanf() function is straightforward. Here are the steps to follow:

  1. Open the file you want to read from using the fopen() function in read-only mode, and verify it returned a valid resource.
  2. Use a loop that checks the return value of fscanf(), since it reads tokens based on the format string rather than fixed lines and may span multiple lines or stop at whitespace.
  3. Call fscanf() inside the loop, passing the file pointer, format string, and pre-initialized variables. Check its return value to handle errors or unexpected end-of-file.
  4. Close the file using the fclose() function.

Here's an example code snippet that demonstrates how to use the fscanf() function:

How to Use the fscanf() Function?

php
<?php
$filename = 'data.txt';
$file = fopen($filename, 'r');

if ($file === false) {
    die("Error: Could not open file.");
}

while (($count = fscanf($file, "%s %s %d %f", $first_name, $last_name, $age, $salary)) === 4) {
    echo "Name: $first_name $last_name\nAge: $age\nSalary: $salary\n";
}

fclose($file);
?>

In this example, we open the file data.txt using fopen() and verify it returned a valid resource. We then use a while loop that checks the return value directly, preventing infinite loops if fscanf() encounters an incomplete line or EOF. fscanf() modifies the variables by reference and returns the number of fields successfully assigned; the loop continues only when all four fields are read. Common format specifiers include %s (string), %d (integer), %f (float), and %c (single character). Finally, we output the data and close the file with fclose().

Related Functions For similar tasks, consider sscanf() for parsing formatted strings instead of files, or fgetcsv() for reading CSV files line by line.

Conclusion

The fscanf() function is a useful tool in PHP for reading formatted data from files. By following the steps outlined in this guide, you can easily use the fscanf() function in your PHP projects to read formatted data from files.

Practice

What is the function of fscanf() in PHP?

Dual-run preview — compare with live Symfony routes.