How can the fwrite function in PHP be optimized for writing data to a file in a more efficient manner?

When using the fwrite function in PHP to write data to a file, it can be optimized by buffering the data before writing it to the file. This can be achieved by using the PHP output buffering functions like ob_start() and ob_get_clean() to collect the data in a buffer and then write it to the file in one go.

<?php
$file = 'data.txt';
$data = 'Hello, World!';

ob_start();
fwrite($file, $data);
ob_get_clean();