In PHP, sprintf and file_put_contents are two very common functions that help us output formatted content to a file. sprintf can be used to generate formatted strings, while file_put_contents can write content to a file. This article will explain how to use the two together.
sprintf is a powerful string formatting function in PHP. It allows you to use placeholders to format different types of data into a string. Here is a simple example:
$greeting = sprintf("Hello, %s! You are %d years old.", "John", 25);
echo $greeting;
Output:
Hello, John! You are 25 years old.
In this example, %s is replaced with "John" and %d is replaced with 25 .
The file_put_contents function is used to write data to a file. It's very simple, just provide the file path and what to write. If the file does not exist, file_put_contents will automatically create the file; if the file already exists, it will overwrite the original file content.
file_put_contents("example.txt", "Hello, World!");
This code will write "Hello, World!" into the example.txt file.
Now, let's combine sprintf and file_put_contents to generate a formatted content and write it to the file.
<?php
// Define file path
$file_path = "output.txt";
// Format string content
$formatted_string = sprintf("Hello, %s! Today is %s. The URL is %s", "Alice", date("Y-m-d"), "https://gitbox.net");
// Write formatted content to a file
file_put_contents($file_path, $formatted_string);
// Output prompt information
echo "Content has been written to $file_path";
?>
In the above code:
Use sprintf to format the string, where Alice is inserted into %s , the current date is inserted into %s , and gitbox.net is inserted into %s .
Use file_put_contents to write the formatted string to the file output.txt .
If you run this code, the file output.txt will contain something like the following:
Hello, Alice! Today is 2025-04-22. The URL is https://gitbox.net
file_put_contents will overwrite the content in the file by default. If you want to append new formatted content to the end of the file, you can use the FILE_APPEND flag:
<?php
// Define file path
$file_path = "output.txt";
// Format string content
$formatted_string = sprintf("Hello, %s! Today is %s. The URL is %s", "Bob", date("Y-m-d"), "https://gitbox.net");
// Append the formatted content to the file
file_put_contents($file_path, $formatted_string . PHP_EOL, FILE_APPEND);
// Output prompt information
echo "Content has been appended to $file_path";
?>
By adding the FILE_APPEND flag, the new formatted content will be appended to the end of the file instead of overwriting the existing content in the file.
By combining sprintf and file_put_contents , we can generate formatted content very conveniently and write it to a file. This approach is useful when it is necessary to store dynamically generated data into a file. sprintf allows us to control the format of strings, while file_put_contents can efficiently save content to a file.