Skip to content

Checking your reading list…

Retry verification

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Using PHP fwrite() to Write Data to Files

Using PHP fwrite() to Write Data to Files

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

fwrite() Function Syntax

fwrite(file, string, length)

Parameter Explanation

file

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

Usage Example

Below is a simple example demonstrating how to use fwrite() to write content to a 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!";
}
?>

In this example, fopen() opens a file named "test.txt" with write mode, fwrite() writes the string "Hello, World!" to the file, and fclose() closes the file. Success or failure messages are echoed accordingly.

Writing Arrays and Other Data Types

The fwrite() function can also write arrays or other data types after serialization. The following example shows how to write a serialized array to a file:

<?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!";
}
?>

Here, an array containing three elements is serialized with serialize() and then written to "data.txt" using fwrite(). After writing, the file is closed and a success message is displayed.

Overall, fwrite() is a versatile function for writing various types of data to files in PHP. When using it, ensure the file is opened with the appropriate mode and that the data type matches the intended write operation.

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

Report an issue with this article
backendPHPTutorialfile handlingfwrite

Reader feedback

Was this useful?

Useful0

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion