PHP fprintf() Function – Complete Guide with Examples

What is fprintf() in PHP?

The fprintf() function in PHP writes formatted data to a file or an output stream, similar to printf(), but instead of displaying output, it writes to a file or resource.

📌 Use cases:
✔ Writing formatted text into files (logs, reports, CSV files).
✔ Sending structured output to streams or sockets.
✔ Formatting log entries with timestamps.

Syntax of fprintf()

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

🔹 Parameters:

  1. $stream → A file handle or resource where data will be written.
  2. $format → A string containing format specifiers (%s, %d, etc.).
  3. $values → The values to be inserted into the format string.

🔹 Return Value:

  • Returns the number of characters written on success.
  • Returns false on failure.

Example: Writing Formatted Data to a File

<?php
$file = fopen("output.txt", "w");
if ($file) {
    fprintf($file, "Name: %s, Age: %d\n", "John Doe", 25);
    fclose($file);
    echo "Data written to file.";
} else {
    echo "Failed to open file.";
}
?>

Output (in output.txt):

Name: John Doe, Age: 25

📌 How it works?

  • Opens output.txt in write mode (w).
  • fprintf() writes "John Doe" and 25 into a structured string.
  • Closes the file using fclose().

Example: Writing Log Entries with Timestamps

<?php
$logFile = fopen("log.txt", "a"); // Open in append mode
if ($logFile) {
    fprintf($logFile, "[%s] ERROR: %s\n", date("Y-m-d H:i:s"), "Database connection failed!");
    fclose($logFile);
    echo "Log entry added.";
} else {
    echo "Failed to open log file.";
}
?>

Output (log.txt):

[2025-02-12 14:30:45] ERROR: Database connection failed!

📌 Why use fprintf() here?

  • Efficient logging with timestamps.
  • Avoids manual concatenation of strings.
  • Uses append mode (a) to prevent overwriting logs.

Example: Creating a CSV File Using fprintf()

<?php
$file = fopen("users.csv", "w");
if ($file) {
    fprintf($file, "ID,Name,Email\n"); // CSV header
    fprintf($file, "%d,%s,%s\n", 1, "Alice", "alice@example.com");
    fprintf($file, "%d,%s,%s\n", 2, "Bob", "bob@example.com");
    fclose($file);
    echo "CSV file created.";
} else {
    echo "Failed to open file.";
}
?>

Output (users.csv):

ID,Name,Email 1,Alice,alice@example.com 2,Bob,bob@example.com

📌 Why use fprintf() here?

  • Automates structured CSV file creation.
  • Ensures consistent formatting.

Writing to the PHP Output Stream (php://stdout)

<?php
fprintf(STDOUT, "Hello, %s!\n", "PHP Developer");
?>

Output (CLI terminal):

Hello, PHP Developer!

📌 Why use STDOUT?

  • Writes directly to command-line output.
  • Useful for debugging CLI scripts.

Handling Errors with fprintf()

Example: Writing to a Non-Writable File

<?php
$file = fopen("/system/protected.txt", "w"); // Restricted file path
if ($file) {
    fprintf($file, "This won't work!");
    fclose($file);
} else {
    echo "Error: Cannot open file for writing.";
}
?>

Output (if permission denied):

Error: Cannot open file for writing.

📌 Best Practices:

  • Check file permissions before writing.
  • Handle errors to prevent script failure.

Best Practices for Using fprintf()

1. Always Close Files
Use fclose($file); to release resources after writing.

2. Use a (append) Mode for Logs
Prevents overwriting logs when writing new entries.

3. Check File Permissions
Ensure your script has write access before attempting to write.

4. Use STDOUT for CLI Scripts
Great for debugging and command-line output.

5. Format Strings Properly
Use:

  • %s for strings
  • %d for integers
  • %f for floating-point numbers

Alternative Functions to fprintf()

FunctionDescription
printf()Formats and outputs a string to the screen.
sprintf()Formats a string and returns it.
file_put_contents()Writes a string to a file without formatting.
fwrite()Writes raw data to a file without formatting.

📌 Use fprintf() when formatting is required before writing to a file or stream.

When to Use fprintf()

📌 Use fprintf() when:
✔ Writing formatted output to files or streams.
✔ Storing structured logs, reports, or CSV files.
✔ Using PHP CLI scripts with STDOUT.

⚠️ Avoid if:
❌ You only need to print to the screen → Use printf().
❌ You don’t need formatting → Use fwrite().