PHP fprintf function

 The function of the PHP fprintf function can write formatted strings into a file file or data database opened through fopen . For example, if you want to write some text into a text file (.txt) through PHP, you can Use the PHP fprintf function to write, but before using the fprintf function, you must first confirm that the file has been opened with fopen and set the permissions to be writable. As you can see in the example, the fprintf function can write multiple entries at once The variable is inserted into the format string and then written into the file, which is powerful.


PHP fprintf function syntax
fprintf ($handle, $format, $args1, $args2 ...)
The first parameter of the fprintf function, $handle, is an optional item, used to set where to write the string, usually the file opened by fopen. The second parameter $format is a necessary item to set the conversion format. Some formatting codes may be used here. Please refer to the table content of sprinft ". Starting with the third parameter, there can be many $args, but at least one must be filled in. Each $args represents the string to be written in $format in order. For example, $args1 means that the string to be written in $formate is counted from the left. For the first character, $args2 means the second character, and so on, each character will be formatted before writing, fprintf can allow multiple characters to be written into the $formate string at once.

The PHP fprintf function will return the length of the written string after successfully writing the data.

PHP fprintf function example
<?php
  $myfile = fopen("test.txt","w");
  $string = "Wibibi";
  echo fprintf($myfile,"Welcome to %s.",$string);
?>
Example output
18
At the beginning of the example, first open the test.txt file in the root directory of the website through fopen , and set the file permissions to writable, and then prepare a string $string. The third line is the focus of the example, which will be prepared in advance through fprintf The content of the good string $string is first formatted and combined to the position of %s in the string "Welcome to %s." and written to the file pointed to by $myfile, that is, the combined string is written The meaning in the test.txt file. Finally, use echo to output the total length of the string of the entire file written by fprintf (including blanks and symbols), so the result will be 18. If you want to see whether the data is written correctly, you can directly open the file to see. Normal situation It should be visible. If it is not written correctly, please pay attention to whether the permission of fopen to open the file is correct or whether the server has special permission settings. With the help of the PHP fprintf function, designers can easily modify the content of the file.

Post a Comment

0 Comments