fprintf()

fprintf() — Write a formatted string to a stream.

Built-in function of PHP 8.5. The manual lists it as available in PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.

What it does

Write a string produced according to format to the stream resource specified by stream.

Signature

fprintf(resource $stream, string $format, mixed ...$values): int

Parameters

ParameterTypeWhat it takes
$streamresourceA file system pointer resource that is typically created using fopen().
$formatstringAn integer followed by a dollar sign $, to specify which number argument to treat in the conversion.
...$valuesmixed

Return value

Returns the length of the string written.

Example

A runnable snippet:

if (!($fp = fopen('date.txt', 'w'))) { return; } $year = 2005; $month = 5; $day = 6; fprintf($fp, "%04d-%02d-%02d", $year, $month, $day); // will write the formatted ISO date to date.txt

Changelog

VersionChange
8.5.0A formatter that does not specify a precision now correctly treats it as a precision of 0, instead of incorrectly resetting the precision.
8.0.0This function no longer returns false on failure.
8.0.0Throws a ValueError if the number of arguments is zero; previously this function emitted an E_WARNING instead.
8.0.0Throws a ValueError if [width] is less than zero or bigger than PHP_INT_MAX; previously this function emitted an E_WARNING instead.
8.0.0Throws a ValueError if [precision] is less than zero or bigger than PHP_INT_MAX; previously this function emitted an E_WARNING instead.
8.0.0Throws an ArgumentCountError when fewer arguments are given than required; previously this function emitted an E_WARNING instead.

See also

printf(), sprintf(), vprintf(), vsprintf(), vfprintf(), sscanf(), fscanf(), number_format(), date()

All PHP 8.5 built-in functions

Reference card built from the PHP manual page fprintf() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.