Home >>PHP String Functions >PHP fprintf() Function
PHP fprintf() function is used to write a string in a defined format to any specific Output stream like any file or any database. In this fprintf() function we can pass many number of variables as we need in the string.
The very first parameter is $stream which contains the stream value that defines where the string is to be write or return as output.
$format defines the format in which the string is to be sent or inserted in the database or file.
$arg1 is the argument which is to be inserted at first. $stream , $format, and $arg1 are required parameters where as other parameters are optional. $arg2 is the argument which is to be inserted at second, and $arg++ are the arguments which are to be inserted next.
Syntax :
fprintf($stream,$format,$arg1,$arg2,$arg++);
Here is an example of fprintf() function in PHP:
<html> <body> <?php $age = 21; $name = "Abhi"; $file = fopen("file.txt","w"); echo fprintf($file,"%s is %u years old.",$name,$age); ?> </body> </html>
The above code will write the string in the format "Abhi is 21 years old". In the given "file.txt" file.
There are many different possible format values, some of which are:-
<html> <body> <?php $num1 = 123456789; $num2 = -123456789; printf("%%b = %b <br>",$num1); // Binary number printf("%%d = %d <br>",$num1); // Signed decimal number printf("%%e = %e <br>",$num1); // Scientific notation (lowercase) printf("%%E = %E <br>",$num1); // Scientific notation (uppercase printf("%%u = %u <br>",$num2); // Unsigned decimal number (negative) printf("%%f = %f <br>",$num1); // Floating-point number (local settings aware) printf("%%F = %F <br>",$num1); // Floating-point number (not local sett aware) printf("%%g = %g <br>",$num1); // Shorter of %e and %f printf("%%G = %G <br>",$num1); // Shorter of %E and %f printf("%%o = %o <br>",$num1); // Octal number printf("%%s = %s <br>",$num1); // String printf("%%x = %x <br>",$num1); // Hexadecimal number (lowercase) printf("%%X = %X <br>",$num1); // Hexadecimal number (uppercase) ?> </body> </html>
Note : The format value "%%" returns a percent sign