PHP fprintf() Function
Topic: PHP String ReferencePrev|Next
Description
The fprintf()
function writes a formatted string to a stream, usually a file.
This function takes a special format string and then any number of other arguments, which will be formatted and spliced into the specified places in the format string to generate the result.
Related functions: printf()
, sprintf()
, vfprintf()
, vprintf()
and vsprintf()
.
The following table summarizes the technical details of this function.
Return Value: | Returns the length of the string written. |
---|---|
Version: | PHP 5+ |
Syntax
The basic syntax of the fprintf()
function is given with:
The following example shows the fprintf()
function in action.
Example
Run this code »<?php
$file = "data.txt";
// Open the file for writing
$handle = fopen($file, "w") or die("ERROR: Cannot open the file.");
// Sample strings
$count = 50;
$country = "United States";
$format = "There are %d states in the %s.";
// Formatting and write the string to file
$length = fprintf($handle, $format, $count, $country);
echo "Wrote $length bytes to data.txt";
?>
The output of the above example will look something like this:
And, the text written to the file "data.txt" will be:
In the above example, if the "data.txt" file doesn't exist PHP will automatically create it and write the data. But, if the "data.txt" file already exist, PHP will erase the contents of this file, if it has any, before writing the new data. See the tutorial on PHP file system to learn more about it.
Note: Every character in the format string will be written literally, except the % character and characters that immediately follow it. The % character indicates the beginning of a conversion specification, which specifies how to print the arguments that follow the format string.
Tip: The fprintf()
function is very similar to printf()
except that the printf()
function outputs a text string directly, similar to the print
and echo
statements, whereas the fprintf()
function writes the output to a file.
Parameters
The fprintf()
function accepts the following parameters.
Parameter | Description |
---|---|
stream | Required. Specifies a file system pointer resource that is typically created using fopen() . |
format | Required. Specifies the format string. It is composed of ordinary characters (excluding %) and one or more conversion specifications. |
arg1 | Required. Specifies the argument to be formatted and inserted at the position of first conversion specification in the format string. |
arg2 | Optional. Specifies the argument to be formatted and inserted at the position of second conversion specification in the format string. |
argN | Optional. Specifies the argument to be formatted and inserted at the position of Nth conversion specification in the format string. |
Conversion Specification Syntax
This section describes the syntax of conversion specification in the format string in detail.
A conversion specification begins with a percent symbol (%). You must include a conversion specification for each argument that is passed to the fprintf()
function after the format string.
Alternatively, you can use the argument number followed by a dollar sign (i.e. argnum$
) to apply multiple conversion specifications in the format string to the same argument. It must come immediately after the percent sign (%), before any other specifiers. See more examples section.
A conversion specification typically has the following syntax:
%[argnum$][flags][width][.precision]specifier
argnum
An integer followed by a dollar sign $, to specify which number argument to treat in the conversion.
flags
The flags consist of one or more of the following characters:
Flag | Description |
---|---|
+ |
Adds a plus sign before positive numbers. By default, only negative numbers are marked. |
- |
Left-justify within the given field width; Right justification is the default. |
(space) |
Pads the result with spaces. This is the default. |
0 |
Only left-pads numbers with zeros. With s specifiers this can also right-pad with zeros. |
'(char) |
Pads the result with the character (char). Must be used together with the width specifier. |
width
An integer that indicates how many characters (minimum) this conversion should result in.
precision
A period (.) followed by an integer who's meaning depends on the specifier:
- For e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6).
- For g and G specifiers: this is the maximum number of significant digits to be printed.
- For s specifier: it acts as a cutoff point, setting a maximum character limit to the string.
If the period is specified without an explicit value for precision, 0 is assumed.
specifier
A single character indicating how the type of the argument should be interpreted.
specifier | Description |
---|---|
% |
A literal percent character. No argument is required. |
b |
The argument is treated as an integer and printed as a binary number. |
c |
The argument is treated as an integer and printed as the character with that ASCII. |
d |
The argument is treated as an integer and printed as a (signed) decimal number. |
e |
The argument is treated as as scientific notation (e.g. 1.2e+2). The precision specifier stands for the number of digits after the decimal point. |
E |
Like the e specifier but uses uppercase letter (e.g. 1.2E+2). |
f |
The argument is treated as as a float and printed as a floating-point number (locale aware). |
F |
The argument is treated as as a float and printed as a floating-point number (non-locale aware). |
g |
General format. Uses e and f. |
G |
Like the g specifier but uses E and f. |
o |
The argument is treated as an integer and printed as an octal number. |
s |
The argument is treated and printed as a string. |
u |
The argument is treated as an integer and printed as an unsigned decimal number. |
x |
The argument is treated as an integer and printed as a hexadecimal number (lowercase letters). |
X |
The argument is treated as an integer and printed as a hexadecimal number (uppercase letters). |
More Examples
Here're some more examples showing how fprintf()
function actually works:
The following example shows how to apply multiple conversion specifications to the same argument.
Example
Run this code »<?php
$file = "data.txt";
// Open the file for writing
$handle = fopen($file, "w") or die("ERROR: Cannot open the file.");
// Sample string
$str = 'star';
$format = 'The polar %1$s is the brightest %1$s in the sky.';
// Formatting and write the string to file
$length = fprintf($handle, $format, $str);
echo "Wrote $length bytes to data.txt";
?>
The output of the above example will look something like this:
And, the text written to the file "data.txt" will be:
Tip: If the format string is enclosed in double-quotes (""), you need to escape the dollar sign after argnum with a backslash character (\), like this %1\$s
, so that the PHP doesn't try to interpret them as variable. Using a backslash like this is called an escape sequence.
The following example shows how to format the same number with and without decimal points.
Example
Run this code »<?php
$file = "data.txt";
// Open the file for writing
$handle = fopen($file, "w") or die("ERROR: Cannot open the file.");
// Sample string
$number = 499;
$format = "The number without decimal points: %1\$d, and the number with two decimal points: %1\$.2f";
// Formatting and write the string to file
$length = fprintf($handle, $format, $number);
echo "Wrote $length bytes to data.txt";
?>
The output of the above example will look something like this:
And, the text written to the file "data.txt" will be:
By default, each conversion specification will be replaced by the formatted argument in the order they are listed inside the function. But, you can swap arguments inside the format string using argnum.
Example
Run this code »<?php
$file = "data.txt";
// Open the file for writing
$handle = fopen($file, "w") or die("ERROR: Cannot open the file.");
// Sample strings
$count = 50;
$country = "United States";
$format = "The %2\$s is a federal republic of %1\$d states.";
// Formatting and write the string to file
$length = fprintf($handle, $format, $count, $country);
echo "Wrote $length bytes to data.txt";
?>
The output of the above example will look something like this:
And, the text written to the file "data.txt" will be:
Tip: If the order of the placeholders or conversion specifications in the format string does not match the order of the arguments listed inside the function. You can use argnum to easily indicate which arguments the placeholders refer to and leave the function code as is.
The following example simply demonstrates what would be the possible outcome when using the different format specifiers for integer values using the printf()
function.
Example
Run this code »<?php
// Sample integers
$num1 = 123456789;
$num2 = -123456789;
$num3 = 65; // ASCII 65 is 'A'
// Notice the double %%, this simply prints a '%' character
printf("%%b = %b <br>", $num1); // Binary representation
printf("%%c = %c <br>", $num3); // The ASCII Character
printf("%%d = %d <br>", $num1); // Standard integer representation
printf("%%d = %d <br>", $num2); // Standard integer representation
printf("%%e = %e <br>", $num1); // Scientific notation (lowercase)
printf("%%E = %E <br>", $num1); // Scientific notation (uppercase)
printf("%%u = %u <br>", $num1); // Unsigned integer representation (positive)
printf("%%u = %u <br>", $num2); // Unsigned integer representation (negative)
printf("%%f = %f <br>", $num1); // Floating-point representation (locale aware)
printf("%%F = %F <br>", $num1); // Floating-point representation (non-locale 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 representation
printf("%%s = %s <br>", $num1); // String representation
printf("%%x = %x <br>", $num1); // Hexadecimal representation (lowercase)
printf("%%X = %X <br>", $num1); // Hexadecimal representation (uppercase)
printf("%%+d = %+d <br>", $num1); // Sign specifier (positive)
printf("%%+d = %+d <br>", $num2); // Sign specifier (negative)
?>
Similarly, the following example shows how to format a string in various ways using s specifier.
Example
Run this code »<?php
$str1 = "Hello";
$str2 = "Hello Alexander!";
printf("[%s]<br>", $str1); // Standard string output
printf("[%10s]<br>", $str1); // Right-justifies the string with spaces
printf("[%-10s]<br>", $str1); // Left-justifies the string value with spaces
printf("[%010s]<br>", $str1); // Left-pads string with zeros.
printf("[%-010s]<br>", $str1); // Right-pads string with zeros
printf("[%'#10s]<br>", $str1); // Left-pads string with '#' character
printf("[%.10s]<br>", $str2); // Cuts off string after 10 characters
?>