How to write to a file in PHP?

Introduction:
To write data into a file, PHP offers functions like file_put_contents() for simplicity or fwrite() when opening a file stream.

Example:

<?php
$filename = "example.txt";
$content = "Hello, PHP file writing!";

if (file_put_contents($filename, $content)) {
    echo "File written successfully.";
} else {
    echo "Failed to write to file.";
}
?>

Explanation:

  • file_put_contents() writes the $content into the file specified by $filename.
  • If the file doesn’t exist, it creates it. If it exists, it overwrites the content by default.
  • Returns true if writing is successful; otherwise false.

Leave a Reply

Your email address will not be published. Required fields are marked *