Master PHP fwrite: Write Files Efficiently with Simple Code Examples

This guide explains PHP's fwrite() function, covering its syntax, parameters, and practical examples for writing strings, arrays, and serialized data to files, while highlighting important considerations such as file opening modes and error handling to ensure successful file operations.

php Courses
php Courses
php Courses
Master PHP fwrite: Write Files Efficiently with Simple Code Examples

The fwrite() function in PHP provides a straightforward and flexible way to write data to files, a common requirement in many applications.

Syntax

fwrite(file, string, length)

Parameters

file

: Required. The file handle obtained from fopen(). string: Required. The data to write; can be a string, array, or other type (must be converted to a string). length: Optional. Maximum number of bytes to write; defaults to the length of the data.

Example: Writing a Simple String

<?php
$file = fopen("test.txt", "w"); // open file in write mode
if ($file) {
    $content = "Hello, World!"; // data to write
    fwrite($file, $content); // write data
    fclose($file); // close file
    echo "Write successful!";
} else {
    echo "Unable to open file!";
}
?>

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

Example: Writing an Array

<?php
$file = fopen("data.txt", "w");
if ($file) {
    $data = array("Zhang San", "Li Si", "Wang Wu");
    fwrite($file, serialize($data)); // serialize array before writing
    fclose($file);
    echo "Write successful!";
} else {
    echo "Unable to open file!";
}
?>

Here an array is serialized with serialize() to convert it into a string, then written to data.txt.

Important Notes

Open the file with a writeable mode such as "w" (write) or "a" (append).

Always verify that fopen() succeeded before calling fwrite().

Close the file with fclose() after writing to release resources.

When writing non‑string data, convert it to a string first (e.g., using serialize() or json_encode()).

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PHPCode Examplefile-handlingfwrite
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

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.