Open In App

PHP fscanf() Function

Last Updated : 28 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The fscanf() function is an inbuilt function in PHP that parses the file’s input according to format, i.e., it accepts the input from a file that is associated with the stream & the input will be interpreted according to the specified format. This function is similar to sscanf() function.

Any whitespace in the input stream is compared with any whitespace in the format string, i.e. the single space character in the input stream will be compared with the tab (\t) in the format string. For every call, this function will read one line from the file.

Syntax:

array|int|false|null fscanf(
    resource $stream, 
    string $format, 
    mixed &...$vars
)

 

Parameters: This function has three parameters, which are described below:

  • stream: The file system pointer resource will be created with the help of the fopen() function.
  • format: The documentation for the sprintf() function describes the interpreted format for strings.
  • vars: This parameter specifies optional values that are assigned to it.

Return Values:

  • The function will return an array if only two values are provided, but if an optional parameter is also passed by reference, it will return the number of assigned values.
  • When there are not enough substrings in the string to match the expected format, null will be returned, and false will be returned for any other errors.

Example 1: This example illustrates the basic use of the fscanf() function in PHP.

PHP




<?php
$file = fopen("text.txt","r") ;
$data = fscanf($file,"%s%s") ;
  
foreach($data as $value){
    var_dump($value)  ;
}
?>


Output:

string(2) "Hi"
string(13) "GeeksforGeeks"                            

Example 2: This is another example that illustrates the basic use of the fscanf() function in PHP.

PHP




<?php
$file = fopen("text.txt","r") ;
$data = fscanf($file,"%s%s") ;
var_dump($data) ; 
?>


Output:

array(2) {
    [0] => string(2) "Hi"
    [1] => string(13) "GeeksforGeeks"
}

Reference: https://www.php.net/manual/en/function.fscanf.php



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads