Example 1 — Write Text to a File
Open a file in write mode, save a greeting, and show how many bytes were written.
<?php
$path = sys_get_temp_dir() . '/fwrite_demo.txt';
$fp = fopen($path, 'w');
$bytes = fwrite($fp, 'Hello, CodeToFun!');
fclose($fp);
echo "Wrote $bytes bytes", PHP_EOL;
echo file_get_contents($path), PHP_EOL;
unlink($path); How It Works
- fopen() with mode w creates the file, or empties it if it already exists.
- fwrite() saves the 17 characters of the greeting and returns 17.
- fclose() finishes the job and releases the file.
- file_get_contents() reads the file back so you can see what was saved.

