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
fwrite(file, string, length)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:
<?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!";
}
?>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:
<?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!";
}
?>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.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
