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

int fprintf ( resource $handle , string $format [, mixed $args [, mixed $... ]] )

The function takes at least two parameters: the file handle of the file to output to ($handle) and the format string ($format). The function also has optional parameters, $args, $..., etc., which represent the values to be inserted into the format string.

Here is an example of how to use the fprintf() function:

<?php
$file = fopen("report.txt", "w");
$name = "John";
$age = 30;
$income = 50000;
fprintf($file, "Name: %s\nAge: %d\nIncome: $%.2f", $name, $age, $income/12);
fclose($file);
?>

In this example, we have a file handle to the file report.txt and some variables that we want to output to the file. We use the fprintf() function to output a formatted string to the file, inserting the values of the variables into the format string. The fclose() function is used to close the file after outputting.

The output of this code will be a new file report.txt containing the following text:

Name: John
Age: 30
Income: $4166.67

As you can see, the fprintf() function has output a formatted string to the file.

Here is another example of how to use the fprintf() function to log an error message:

<?php
$file = fopen("error.log", "a");
$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);
?>

In this example, we have a file handle to a log file error.log and some variables that we want to output to the file. We use the fprintf() function to output a formatted string to the log file, inserting the values of the variables into the format string. The fclose() function is used to close the file after outputting.

The output of this code will be a new line in the error.log file containing the following text:

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

As you can see, the fprintf() function has output a formatted string to the log file.

The fprintf() function is a useful tool for outputting formatted strings to a file. It can help make your code more organized and efficient when working with log files or generating reports. By mastering this function, you can become a more proficient PHP developer.

We hope this article has been helpful in understanding the fprintf()

Practice Your Knowledge

What is the functionality of the 'fprintf' function in PHP, according to the content found on the w3docs website?

Quiz Time: Test Your Skills!

Ready to challenge what you've learned? Dive into our interactive quizzes for a deeper understanding and a fun way to reinforce your knowledge.

Do you find this helpful?