PHP 8.5 fprintf() Function Use With Example

Here is the explanation of the fprintf() function in PHP 8.5, complete with a practical example and the expected output.

PHP 8.5 fprintf() Function

The fprintf() function in PHP is used to write a formatted string directly into a stream (like a file). It is essentially the same as printf(), but instead of sending the output to the browser screen, it saves it directly into a file.

It returns the length (in bytes) of the written string.

Example Code

<?php
// 1. Set up some variables
$product = "Laptop";
$price = 1250.50;
$quantity = 2;

// 2. Open a file to write to (creates invoice.txt if it doesn not exist)
$file = fopen("invoice.txt", "w");

if ($file) {
   // 3. Write the formatted string to the file
   // %s for string, %d for integer, %.2f for float (2 decimal places)
   $bytes_written = fprintf($file, "Item: %s | Qty: %d | Total: $%.2f", $product, $quantity, $price);

   // 4. Close the file
   fclose($file);

   // 5. Output the number of bytes written to the screen
   echo "Success! $bytes_written bytes written to the file.";
}
?>

Output

On your screen (Browser/Command Line):

Success! 38 bytes written to the file.

Inside the invoice.txt file:

Item: Laptop | Qty: 2 | Total: $1250.50

Key Points

%s: Used for the text string ("Laptop").
%d: Used for the whole number/quantity (2).
%.2f: Used for the price, ensuring it shows exactly 2 decimal places (1250.50).
Return Value: The variable $bytes_written catches the number of characters successfully saved to the file (in this case, 38 bytes).
 

8 Views