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. This function is used to read formatted data from files.

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

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.
  2. Call the fscanf() function, passing in the file pointer, the format string, and one or more variables to store the data read.
  3. Use the data read from the file as needed.
  4. Close the file using the fclose() function.

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

<?php

$filename = 'data.txt';
$file = fopen($filename, 'r');
fscanf($file, "%s %s %d %f", $first_name, $last_name, $age, $salary);
echo "Name: $first_name $last_name\nAge: $age\nSalary: $salary";
fclose($file);

In this example, we open the file data.txt using the fopen() function in read-only mode. We then use the fscanf() function to read data from the file, specifying the format of the data to read using the format string "%s %s %d %f". We store the data read in the variables $first_name, $last_name, $age, and $salary. We then output the data using the echo statement before closing the file using the fclose() function.

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 Your Knowledge

What is the function of fscanf() in PHP?

Quiz Time: Test Your Skills!

Ready to challenge what you've learned? Dive into our interactive quizzes for a deeper understanding and a fun way to reinforce your knowledge.

Do you find this helpful?