PHP fscanf function

 The PHP fscanf function can be used to read whether there are strings or characters that meet the normal expression conditions in the file. The usage of the fscanf function is similar to the sscanf function , but the difference is that the fscanf function also has an additional $handle parameter that can be used. Compared with the sscanf function which can only parse the string content, the fscanf function can parse the content of the document file.


Basic syntax of PHP fscanf function

mixed fscanf ( $handle , $format , $mixed ... )


The first parameter of the parentheses of the fscanf function, $handle, is a file system pointer resource, which is a file resource created through fopen . The second parameter, $format, sets the regular expression to be used. For items, please refer to the parameter list on the sprintf function . The third parameter $mixed is the selected item, which can be left blank.

PHP fscanf function example
<?php
$handle = fopen("test.txt", "r");
while ($fscanf_result = fscanf($handle, "%s\t%s\t%s\n")) {
    print_r($fscanf_result);
    echo '<br>';
}
fclose($handle);
?>
The content of the file test.txt being read
ABC
DEF
The output array result parsed by fscanf is as follows
Array( [0] => A [1] => B [2] => C )
Array( [0] => D [1] => E [2] => F )
At the beginning of the example, we used fopen to open the test.txt file in the root directory of the webpage, and then used the while loop to determine the processing result of the fscanf function. If there is a matching string result in the test.txt file, Output the result line through print_r , and finally close the read file resource $handle through the fclose function.

Post a Comment

0 Comments