Using PHP fwrite() to Write Data to Files
This article explains the PHP fwrite() function, its syntax, parameters, and provides clear examples for writing strings and serialized arrays to files, highlighting proper file opening modes and error handling.
Reading font
In PHP, the fwrite() function is used to write data to a file, offering a simple and flexible way to handle common file‑writing tasks.
Syntax
fwrite(file, string, length)Parameters
file: required file handle returned by fopen(). string: required 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 data.
Example – Writing a String
The following example opens test.txt for writing, writes the string “Hello, World!”, and closes the 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!";
}
?>This script demonstrates using fopen() to obtain a file handle, fwrite() to write data, and fclose() to release the resource.
Example – Writing an Array
The next example serializes an array and writes it to data.txt.
<?php
$file = fopen("data.txt", "w");
if ($file) {
$data = array("张三", "李四", "王五");
fwrite($file, serialize($data)); // write serialized array
fclose($file);
echo "Write successful!";
} else {
echo "Unable to open file!";
}
?>By serializing the array with serialize(), the data can be stored in a file and later retrieved.
Overall, fwrite() is a practical function for writing strings, arrays, or other data types to files, provided the file is opened with an appropriate mode.
For questions about attribution, corrections or content rights, please contactand we will review it promptly.