PHP | fscanf() Function

PHP fscanf() Function


Hello folks! welcome back to a new edition of our tutorial on PHP. In this tutorial guide, we are going to be studying about the PHP fscanf() Function.

The PHP fscanf() function parses an input from an open file according to a specified format.

Syntax

Following below is the syntax to use this function -

mixed fscanf ( resource $handle , string $format [, mixed &$... ] )


This built-in function is similar to the built-in sscanf() function. But it can take input from a file which is associated with handle and it can as well interpret an input according a specified format.

Any whitespace that's in the string format can match any whitespace in the input stream, which means that even a tab \t in the string format can match a single space character in the input stream, and each call to fscanf() can read one line from a file.

Example

Try out the below example -

<?php
   $handle = fopen("/PhpProject/Users.txt", "r");
   while($userinfo = fscanf($handle, "%s\t%s\t%s\n")) {
      list($name, $profession, $countrycode) = $userinfo;
   }
   echo $name . "\n";
   echo $profession . "\n";
   echo $countrycode;
   
   fclose($handle);
?>

Output

When the above code is executed, it will produce the following result -

Prince
Designer
NG


Alright guys! This is where we are going to be rounding up for this tutorial post. In our next tutorial, we are going to be discussing about the PHP fseek() Function.

Do feel free to ask your questions where necessary and we will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.