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.
Fundamentals
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.
Foundation
📝 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.
Cheat Sheet
⚡ 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
Hands-On
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.
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.
[09:15:00] INFO | User login (alice)
[09:15:01] WARN | Slow query (orders)
[09:15:02] ERROR | DB timeout (mysql)
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";
?>
📤 Output:
sprintf: Welcome to CodeToFun!
fprintf: Welcome to CodeToFun! (21 bytes)
printf: echoes directly to output
How It Works
sprintf() — returns formatted string (store in variable).
fprintf() — writes to stream (files, memory buffers).
printf() — outputs to stdout (browser/CLI).
Applications
🚀 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.
Important
📝 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.
Wrap Up
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.
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)
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about fprintf()
Use these points whenever you write formatted output in PHP.
5
Core concepts
📝01
Write to Stream
File or memory handle.
Purpose
📈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.