Master PHP’s fwrite(): Write Files Efficiently with Code Examples
Learn how to use PHP’s fwrite() function to write strings, arrays, and other data to files, with clear syntax explanations, parameter details, and practical code examples demonstrating file opening, writing, and closing, plus tips for handling write modes and data types.
In PHP, the fwrite() function is used to write content to a file, providing a simple and flexible way to handle common file‑writing needs.
Syntax of fwrite()
fwrite(file, string, length)Parameter explanations
file: required. The file handle returned by fopen(). string: required. The data to write; can be a string, array, or other type. length: optional. Maximum number of bytes to write; defaults to the length of the string.
Example: Writing a simple string
Using fwrite() to write to a file:
<?php
$file = fopen("test.txt", "w"); // open file for writing
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!";
}
?>The example opens test.txt in write mode, writes "Hello, World!" and closes the file, outputting a success or error message.
Example: Writing an array
Demonstrating how to write an array by serializing it:
<?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!";
}
?>This script creates an array, serializes it with serialize(), writes the result to data.txt, and closes the file.
Overall, fwrite() is a practical function for writing various data types to files; just ensure the file is opened with the correct mode and that the data type matches your needs.
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.
