Using PHP fwrite() to Write Data to Files
This article explains PHP's fwrite() function, detailing its syntax, parameters, and practical examples for writing strings and serialized arrays to files, while highlighting important usage considerations such as file opening modes and data types.
fwrite() Function Syntax
<code>fwrite(file, string, length)</code>Parameter Explanation
file : Required. The file handle returned by fopen() .
string : Required. The data to write; can be a string, array, or other data type.
length : Optional. Maximum number of bytes to write; defaults to the length of the string.
Usage Example
Below is a simple example demonstrating how to use fwrite() to write content to a file:
<code><?php
$file = fopen("test.txt", "w"); // open file in write mode
if ($file) {
$content = "Hello, World!"; // content to write
fwrite($file, $content); // write to file
fclose($file); // close file
echo "Write successful!";
} else {
echo "Unable to open file!";
}
?>
</code>In this example, fopen() opens a file named "test.txt" with write mode, fwrite() writes the string "Hello, World!" to the file, and fclose() closes the file. Success or failure messages are echoed accordingly.
Writing Arrays and Other Data Types
The fwrite() function can also write arrays or other data types after serialization. The following example shows how to write a serialized array to a file:
<code><?php
$file = fopen("data.txt", "w");
if ($file) {
$data = array("Zhang San", "Li Si", "Wang Wu");
fwrite($file, serialize($data)); // write serialized array
fclose($file);
echo "Write successful!";
} else {
echo "Unable to open file!";
}
?>
</code>Here, an array containing three elements is serialized with serialize() and then written to "data.txt" using fwrite() . After writing, the file is closed and a success message is displayed.
Overall, fwrite() is a versatile function for writing various types of data to files in PHP. When using it, ensure the file is opened with the appropriate mode and that the data type matches the intended write operation.
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.