PHP program to write text to a file

By IncludeHelp Last updated : January 7, 2024

Problem statement

Write a PHP program to write text to a file.

Writing text to a file

To write text (data) to a file, use the file_put_contents() function. It accepts the file name and the data to write to the file. On the successful execution of the function, it returns the number of bytes that were written to the file; False, on failure.

Note

The file_put_contents() function creates and writes the data if the file does not exist. If a file exists, then it appends the data.

PHP program to write text to a file

Here, we have a file "file.txt", we will write some data to this file.

<?php
// Take the file name
$file_name = "file.txt";

// text to write to the file
$content = "Hello, world! How're You?";

// write data to the file
$result = file_put_contents($file_name, $content);

// printing the result
if ($result > 0) {
    echo $result . " bytes/characters have been written to file";
} else {
    echo "There is some error.";
}
?>

Output

The output of the above program is:

25 bytes/characters have been written to file

File's content is:

Hello, world! How're You?

To understand the above program, you should have the basic knowledge of the following PHP topics:

More PHP File Handling Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.