Backend Development 4 min read

Using PHP's fwrite() Function to Write Data to Files

This article explains PHP's fwrite() function, its syntax and parameters, and provides clear code examples for writing strings and serialized arrays to files, while highlighting important considerations such as file opening modes and data types.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP's fwrite() Function to Write Data to Files

In PHP, the fwrite() function is used to write content to a file, offering a simple and flexible way to handle common file‑writing tasks.

Syntax of fwrite()

<code>fwrite(file, string, length)</code>

Parameter Explanation

file : required; the file handle returned by fopen() .

string : required; the data to write, which can be a string, array, or other data type.

length : optional; the maximum number of bytes to write, defaulting to the length of the data.

fwrite() Usage Example

The following example demonstrates writing a simple string to a file:

<code>&lt;?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!";
}
?&gt;</code>

This code opens test.txt for writing, writes the string "Hello, World!", closes the file, and outputs a success or failure message.

Writing Arrays and Other Data Types

Beyond strings, fwrite() can write arrays or other data types after serialization. The example below writes a serialized array to a file:

<code>&lt;?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!";
}
?&gt;</code>

Here, an array containing three elements is serialized with serialize() and then written to data.txt .

The fwrite() function is a practical tool for file output in PHP; when using it, ensure the file is opened with the correct mode and that the data type matches the intended write operation.

Backendfile-handlingfwritephp-io
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.