Current Location: Home> Latest Articles> PHP fscanf() Function Explained: Usage, Parameters, and Example

PHP fscanf() Function Explained: Usage, Parameters, and Example

M66 2025-10-24

Introduction to PHP fscanf() Function

In PHP, the fscanf() function is used to parse input from an open file according to a specified format. It is commonly used to read formatted data such as strings, integers, or floating-point numbers from files.

Syntax of fscanf()

fscanf(file_pointer, format, mixed)

Here, file_pointer is a file resource opened by fopen(), format specifies the reading pattern, and mixed represents optional variables to store the parsed values.

Parameter Details

  • file_pointer: A file pointer resource created using fopen().
  • format: Specifies the format for input data. Common format specifiers include:
  • %% - Returns a percent sign
  • %b - Binary number
  • %c - Character according to ASCII value
  • %f or %F - Floating-point number
  • %o - Octal number
  • %s - String
  • %d - Signed decimal number
  • %e - Scientific notation
  • %u - Unsigned decimal number
  • %x - Lowercase hexadecimal number
  • %X - Uppercase hexadecimal number
  • mixed: Optional. Specifies the variables to assign the parsed values to.

Return Value

If only two parameters are provided, fscanf() returns the parsed values as an array. If additional parameters are provided, the results are assigned directly to the specified variables.

Example of fscanf() Function

<?php
   $file_pointer = fopen("new.txt", "r");
   while ($playerrank = fscanf($file_pointer, "%s\t%d\n")) {
       list($name, $rank) = $playerrank;
       echo "$name got rank $rank.";
   }
   fclose($file_pointer);
?>

Output

Amit got rank 2

Conclusion

The fscanf() function is a powerful tool for reading structured data from files. By using the right formatting parameters, developers can easily extract and process specific types of information from text files, improving both readability and efficiency of PHP applications.