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.
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
<code>fwrite(file, string, length)</code>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.
<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>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 .
<code><?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!";
}
?></code>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.
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.