The fprintf Function
The fprintf
function formats a string according to the specified pattern and writes the result to a file stream. The first parameter accepts a file resource, the second - a format string, and the subsequent parameters - values for substitution into the template. If you pass null instead of a file resource, the function will return a string instead of writing to the stream.
The format string uses special characters (format specifiers), which start with the %
sign and control the output formatting.
Syntax
fprintf(resource $handle, string $format, mixed ...$values): int|false
Format Specifiers
Specifier | Description |
---|---|
%s |
String |
%d |
Signed integer (decimal) |
%u |
Unsigned integer (decimal) |
%f |
Floating-point number (locale dependent) |
%F |
Floating-point number (not locale dependent) |
%c |
Character by ASCII code |
%x |
Integer in hexadecimal system (lowercase) |
%X |
Integer in hexadecimal system (uppercase) |
%o |
Integer in octal system |
%b |
Integer in binary system |
%e |
Scientific notation (lowercase) |
%E |
Scientific notation (uppercase) |
%g |
Short representation of %e or %f |
%G |
Short representation of %E or %F |
%% |
Percent sign |
Example
Writing a formatted string to a file:
<?php
$file = fopen('output.txt', 'w');
fprintf($file, "Name: %s, Age: %d", "John", 25);
fclose($file);
?>
Contents of the output.txt file:
'Name: John, Age: 25'
Example
Using different format specifiers:
<?php
$res = fopen('php://temp', 'w');
fprintf($res, "Float: %.2f, Hex: %x", 12.3456, 255);
rewind($res);
echo stream_get_contents($res);
fclose($res);
?>
Code execution result:
'Float: 12.35, Hex: ff'
Example
Returning a string instead of writing to a file:
<?php
$result = sprintf("Today is %s", date('Y-m-d'));
echo $result;
?>
Code execution result:
'Today is 2023-11-15'
See Also
-
the
sprintf
function,
which returns a formatted string -
the
vprintf
function,
which outputs a formatted string -
the
file_put_contents
function,
which writes data to a file