How to Use PHP's file_put_contents() for Writing Data to Files
This article explains the PHP file_put_contents() function, its syntax, parameters, return values, and provides practical code examples for writing strings, appending data, handling arrays, and using callbacks to dynamically generate file content.
In PHP development, handling files is a common task, and the file_put_contents() function offers a simple and efficient way to write data to a file without manually opening and closing it.
Function Syntax
file_put_contents(string $filename, mixed $data, int $flags = 0, resource $context = null): false|intParameter Description
$filename : the target file name.
$data : the data to write, which can be a string, an array, or a callback that returns a string.
$flags : optional flags for additional write options; default is 0 (no extra options).
$context : optional stream context resource.
Return Value
On success, returns the number of bytes written.
On failure, returns false .
Below are several concrete code examples demonstrating the use of file_put_contents() :
1. Write a string to a file
$filename = 'test.txt';
$data = 'Hello, world!';
file_put_contents($filename, $data);This creates test.txt in the current directory and writes "Hello, world!" into it.
2. Append a string to a file
$filename = 'test.txt';
$data = 'Hello, world again!';
file_put_contents($filename, $data, FILE_APPEND);The FILE_APPEND flag appends the string to the existing file content.
3. Write an array to a file
$filename = 'test.txt';
$data = ['apple', 'banana', 'orange'];
file_put_contents($filename, implode("\n", $data));This joins the array elements with newline characters and writes them to the file.
4. Write data generated by a callback
$filename = 'test.txt';
$data = function(){
return date('Y-m-d H:i:s');
};
file_put_contents($filename, $data());An anonymous function returns the current timestamp, which is then written to the file.
In practice, file_put_contents() can be combined with other functions such as fopen() / fwrite() / fclose() or file_get_contents() for more complex file operations.
Conclusion
The file_put_contents() function is a convenient PHP file‑handling utility that simplifies writing data to files. It supports flexible parameters for strings, arrays, and callbacks, and can easily handle both new writes and appends, reducing code size and improving file‑write efficiency in backend development.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.