W3docs

fprint()

The fprintf() function is used to output a formatted string to a file. The syntax of the fprintf() function is as follows:

The PHP fprintf() function writes a formatted string to an open file (stream). Think of it as printf() — which prints to the browser/output — but with the destination redirected to a file handle. It is the natural choice when you want clean, aligned, predictable text in a log file or a generated report, instead of building strings by hand with concatenation.

This page covers the syntax, the format specifiers you'll use most, two complete runnable-style examples, and the closely related functions you can reach for instead.

Syntax

int fprintf ( resource $handle , string $format [, mixed ...$args ] )
ParameterRequiredDescription
$handleYesA file stream resource returned by fopen().
$formatYesThe format string. Plain text is written as-is; % placeholders are replaced by $args.
$argsNoOne value per % placeholder, in order.

The function returns the number of bytes written, or false on failure. Note that the return value is the length of the written string, not the number of arguments — useful when you need to track how much data you've logged.

Format specifiers

The power of fprintf() is in the $format string. Each % introduces a placeholder:

SpecifierMeaningExample output
%sStringJohn
%dInteger (signed)30
%fFloat4166.666667
%.2fFloat, 2 decimals4166.67
%05dInteger, zero-padded to width 500042
%xHexadecimal1a
%%A literal % sign%

The same specifiers work in printf() and sprintf(), so once you learn them here they carry over everywhere.

Writing a report

Here is a complete example that writes a small report to a file.

<?php
$file = fopen("report.txt", "w");
if ($file === false) {
    die("Failed to open file");
}
$name = "John";
$age = 30;
$income = 50000;
// \$ prints a literal dollar sign; %.2f rounds the float to 2 decimals
$bytes = fprintf($file, "Name: %s\nAge: %d\nIncome: \$%.2f", $name, $age, $income / 12);
fclose($file);

echo "$bytes bytes written"; // 35 bytes written
?>

We open report.txt for writing ("w") and check that fopen() did not fail. fprintf() then substitutes each variable into the format string: %s for the name, %d for the age, and \$%.2f for the monthly income (a literal $ followed by a float rounded to two decimals). Always call fclose() when you're done so the buffer is flushed and the handle is released.

The resulting report.txt contains:

Name: John
Age: 30
Income: $4166.67

50000 / 12 is 4166.6667, which %.2f rounds to 4166.67.

Appending to a log file

A very common use is appending one formatted line to a log. Open the file in append mode ("a") so each call adds a new line instead of overwriting the previous content:

<?php
$file = fopen("error.log", "a");
if ($file === false) {
    die("Failed to open file");
}
$error_code = 404;
$date = date("Y-m-d H:i:s");
$ip_address = $_SERVER['REMOTE_ADDR'];
fprintf($file, "[%s] Error %d from IP address %s\n", $date, $error_code, $ip_address);
fclose($file);
?>

Because the file is opened with "a", each run appends one new line; nothing already in error.log is lost. The \n at the end of the format string puts each entry on its own line. A typical appended line looks like:

[2023-03-15 15:30:00] Error 404 from IP address 192.168.0.1

Choosing the right tool keeps your code clear:

  • printf() — same formatting, but writes to standard output (the browser/CLI) instead of a file.
  • sprintf() — returns the formatted string instead of writing it anywhere, so you can store or reuse it.
  • fwrite() — writes raw bytes to a file with no formatting; use it when you don't need % placeholders.
  • vfprintf() — like fprintf(), but takes the arguments as a single array instead of a variadic list.

Common gotchas

  • Mismatched specifiers and arguments. %d on a non-numeric string yields 0; passing fewer arguments than placeholders triggers a warning.
  • Forgetting to escape %. To print a literal percent sign, use %%, not %.
  • Forgetting fclose(). Buffered data may not be flushed to disk until the handle is closed (or the script ends).
  • Open mode matters. "w" truncates the file; "a" appends. Pick deliberately.

Practice

Practice
What is the functionality of the 'fprintf' function in PHP, according to the content found on the w3docs website?
What is the functionality of the 'fprintf' function in PHP, according to the content found on the w3docs website?
Was this page helpful?