312 of 410 menu

The vfprintf Function

The vfprintf function writes a string formatted according to specifiers to a file stream. The first parameter accepts a file resource, the second - a format string, the third - an array of arguments for substitution. The format string uses special characters (format specifiers) that start with the % sign and control the output formatting.

Syntax

vfprintf(resource $handle, string $format, array $args): int

Format Specifiers

Specifier Description
%s String
%d Signed integer (decimal)
%u Unsigned integer (decimal)
%f Floating-point number (locale-dependent)
%F Floating-point number (non-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'); $values = [10, 20.5, 'test']; vfprintf($file, "Number: %d, Float: %.2f, String: %s", $values); fclose($file); ?>

Contents of the output.txt file:

'Number: 10, Float: 20.50, String: test'

Example

Using different specifiers:

<?php $res = fopen('php://output', 'w'); $data = [15, 12.3456, 'ABCDE']; vfprintf($res, "Hex: %x, Scientific: %.2e, Padding: '%5s'", $data); fclose($res); ?>

Output result:

'Hex: f, Scientific: 1.23e+1, Padding: \' ABCDE\''

See Also

  • the fprintf function,
    which formats a string and writes it to a stream
  • the sprintf function,
    which returns a formatted string
  • the vsprintf function,
    which works like sprintf but accepts an array of arguments
byenru