PHP fprintf() Function

Beginner
⏱️ 9 min read
📚 Updated: Jul 2026
🎯 5 Examples
String Functions

What You’ll Learn

The fprintf() function writes a formatted string directly to a stream—typically a file opened with fopen(). It shares format specifiers with sprintf() and printf(), but targets a file handle instead of returning or echoing text.

01

Write to Stream

File or memory buffer.

02

Format String

%s, %d, %.2f, etc.

03

Returns int

Bytes written count.

04

vs sprintf()

File vs string return.

05

vs printf()

Stream vs stdout.

06

Log Files

Structured file output.

Definition and Usage

In PHP, fprintf() combines string formatting with stream I/O. You pass a stream resource (from fopen()), a format string with placeholders, and the values to insert. PHP writes the formatted result to the stream and returns how many bytes were written.

💡
Beginner Tip

The first argument is a stream resource, not a plain string. If you only need a formatted string in a variable, use sprintf(). If you want to echo directly, use printf(). Choose fprintf() when writing to log files, exports, or any fopen() handle.

📝 Syntax

The fprintf() function requires a stream, a format string, and optional values:

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

Parameters

  • $stream — a file pointer resource from fopen() (file, php://memory, etc.). Must be opened in a write-capable mode.
  • $format — format string with conversion specifiers like %s (string), %d (integer), %.2f (float with 2 decimals).
  • ...$values — values inserted into the format placeholders in order.

Return Value

Returns the number of bytes written to the stream. Since PHP 8.0, invalid arguments throw ValueError or ArgumentCountError instead of returning false.

⚡ Quick Reference

String
fprintf($fp, "Hello, %s!", $name)

%s = string

Padded date
fprintf($fp, "%04d-%02d-%02d", $y, $m, $d)

Zero-padded ISO date

Currency
fprintf($fp, "%.2f", $amount)

Two decimal places

In memory
fopen('php://memory', 'rw+')

Test without a file

Examples Gallery

Run these examples in PHP 7+. Each demonstrates a common pattern beginners encounter with fprintf().

📚 Getting Started

Format text and write it to a stream.

Example 1 — Write to a Memory Stream

Use php://memory to test fprintf() without creating a real file on disk.

PHP
<?php
$stream = fopen('php://memory', 'rw+');

$bytes = fprintf($stream, "Hello, %s!", "PHP");

rewind($stream);
$output = stream_get_contents($stream);
fclose($stream);

echo "Written: $output\n";
echo "Bytes:   $bytes\n";
?>

How It Works

fprintf() writes to the stream; rewind() moves the pointer back so you can read the buffer with stream_get_contents(). The return value is the byte count written.

Example 2 — Zero-Padded Date (PHP Manual Pattern)

Format integers with width and zero-padding—ideal for ISO dates and fixed-width columns.

PHP
<?php
$stream = fopen('php://memory', 'rw+');

$year  = 2005;
$month = 5;
$day   = 6;

fprintf($stream, "%04d-%02d-%02d", $year, $month, $day);

rewind($stream);
echo stream_get_contents($stream) . "\n";

fclose($stream);
?>

How It Works

  • %04d — integer padded to 4 digits with leading zeros.
  • %02d — integer padded to 2 digits (5 becomes 05).
  • Same specifiers work when writing to a real file like date.txt.

📈 Practical Patterns

Currency formatting, logging, and comparison with sprintf().

Example 3 — Format Currency with Decimals

Control decimal precision when writing monetary values to a file or export.

PHP
<?php
$stream = fopen('php://memory', 'rw+');

$price1 = 68.75;
$price2 = 54.35;
$total  = $price1 + $price2;

$bytes = fprintf($stream, '%.2f', $total);

rewind($stream);
$written = stream_get_contents($stream);
fclose($stream);

echo "Total:   $total\n";
echo "Written: $written\n";
echo "Bytes:   $bytes\n";
?>

How It Works

Floating-point addition gives 123.1, but %.2f always writes two decimal places: 123.10. Use the return value to track how many bytes were written.

Example 4 — Write Structured Log Lines

Combine multiple specifiers to build consistent log or CSV output in one call.

PHP
<?php
$stream = fopen('php://memory', 'rw+');

$entries = [
    ["09:15:00", "INFO",  "User login",  "alice"],
    ["09:15:01", "WARN",  "Slow query",  "orders"],
    ["09:15:02", "ERROR", "DB timeout",  "mysql"],
];

foreach ($entries as [$time, $level, $msg, $ctx]) {
    fprintf($stream, "[%s] %-5s | %s (%s)\n", $time, $level, $msg, $ctx);
}

rewind($stream);
echo stream_get_contents($stream);
fclose($stream);
?>

How It Works

%-5s left-justifies the log level in 5 characters. Replace php://memory with fopen('app.log', 'a') to append to a real log file.

Example 5 — fprintf() vs sprintf() vs printf()

Three related functions—same format specifiers, different output destinations.

PHP
<?php
$name = "CodeToFun";

// sprintf — returns a string
$text = sprintf("Welcome to %s!", $name);
echo "sprintf:  $text\n";

// fprintf — writes to a stream, returns byte count
$stream = fopen('php://memory', 'rw+');
$bytes  = fprintf($stream, "Welcome to %s!", $name);
rewind($stream);
echo "fprintf:  " . stream_get_contents($stream) . " ($bytes bytes)\n";
fclose($stream);

// printf — echoes directly (commented to keep output tidy)
// printf("Welcome to %s!\n", $name);
echo "printf:   echoes directly to output\n";
?>

How It Works

  • sprintf() — returns formatted string (store in variable).
  • fprintf() — writes to stream (files, memory buffers).
  • printf() — outputs to stdout (browser/CLI).

🚀 Common Use Cases

  • Log files — append timestamped, formatted entries with fopen('app.log', 'a').
  • CSV and data exports — write fixed-width or delimited rows efficiently.
  • Report generation — produce formatted text files (dates, currency, IDs).
  • Incremental buffers — build large strings in memory via php://memory.
  • CLI scripts — write formatted output to STDERR or custom streams.

🧠 How fprintf() Works

1

Open a stream

Use fopen() to get a writable stream—a file, memory buffer, or standard I/O handle.

Input
2

Format string is processed

PHP replaces placeholders (%s, %d, etc.) with your values, applying width and precision rules.

Transform
3

Bytes are written to stream

The formatted text is appended to the stream at the current file pointer position.

Output
=

Byte count returned

The integer return value tells you exactly how many bytes were written.

📝 Notes

  • The first argument must be a stream resource, not a plain string (fix from older tutorials).
  • Always fclose() streams when finished to free resources.
  • Since PHP 8.0, missing format arguments throw ArgumentCountError.
  • Use 'a' mode to append logs; 'w' overwrites existing files.
  • For simple string building without files, sprintf() is often clearer.

Conclusion

The fprintf() function writes formatted text directly to streams, making it ideal for log files, exports, and buffered output. It shares format specifiers with sprintf() and printf() but targets a file handle you control.

Open your stream with fopen(), write with fprintf(), and close with fclose(). Use php://memory when learning or testing without touching the filesystem.

💡 Best Practices

✅ Do

  • Check that fopen() succeeded before calling fprintf()
  • Use php://memory for testing formatted output
  • Close streams with fclose() when done
  • Use %.2f, %04d for consistent numeric formatting
  • Prefer sprintf() when you only need a string variable

❌ Don’t

  • Pass a plain string as the first argument (must be a stream)
  • Forget to open the file in write or append mode
  • Leave file handles open after writing
  • Use fprintf() when file_put_contents() suffices for simple writes
  • Mix up argument order with implode() (different function entirely)

Key Takeaways

Knowledge Unlocked

Five things to remember about fprintf()

Use these points whenever you write formatted output in PHP.

5
Core concepts
📈 02

Format Specifiers

%s, %d, %.2f.

Syntax
🛠 03

Returns Bytes

Integer byte count.

Return
🔄 04

vs sprintf()

Stream vs string.

Compare
05

Log Files

Structured output.

Use case

❓ Frequently Asked Questions

fprintf() writes a formatted string directly to a stream (usually a file opened with fopen()). It uses the same format specifiers as sprintf() and printf(), but sends output to a file handle instead of returning or echoing it.
int fprintf(resource $stream, string $format, mixed ...$values). The first argument is a stream resource from fopen(), not a plain string. The format string uses placeholders like %s, %d, and %.2f.
sprintf() returns the formatted string. fprintf() writes it to a stream and returns the number of bytes written. Use fprintf() when writing to files; use sprintf() when you need the string in a variable.
It returns an integer—the number of bytes written to the stream. Since PHP 8.0, it throws exceptions on invalid arguments instead of returning false.
Yes. Open php://memory with fopen('php://memory', 'rw+') to write to an in-memory buffer, then read it back with stream_get_contents()—useful for testing and building strings incrementally.
printf() sends formatted output directly to standard output (the browser or CLI). fprintf() writes to a specific stream you provide, such as a log file or memory buffer.

Explore More PHP String Functions

Continue with get_html_translation_table(), htmlspecialchars(), and the rest of the string function reference.

Next: get_html_translation_table() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful