The SplFileObject::fflush() function is an inbuilt function in the Standard PHP Library (SPL) in PHP that is used to flush the output buffer of the file.
Syntax:
public SplFileObject::fflush():bool
Parameter: This function does not accept any parameters.
Return Value: The SplFileObject::fflush() function returns “true” if the function successfully flushes the output buffer of the file otherwise, this function will return “false”.
Program 1: The following program demonstrates the SplFileObject::flush() function. The “output.txt” should be available in the same folder.
PHP
<?php $file = new SplFileObject( "output.txt" , "w" ); $data = "This is some data that will be written to the file.\n" ; $file ->fwrite( $data ); // Flush the data to the file immediately if ( $file -> fflush ()) { echo "Data flushed successfully to the file." ; } else { echo "Failed to flush data to the file." ; } ?> |
Output:
Data flushed successfully to the file.
Program 2: The following program demonstrates SplFileObject::flush() function. The “output.txt” should be available in the same folder.
PHP
<?php $file = new SplFileObject( "output.txt" , "w" ); $dataLines = [ "Line 1: This is the first line of data.\n" , "Line 2: This is the second line of data.\n" , "Line 3: This is the third line of data.\n" , ]; foreach ( $dataLines as $line ) { // Write the line to the file $file ->fwrite( $line ); // Flush the data to the file // immediately after writing each line if ( $file -> fflush ()) { echo "Data flushed successfully for line: " . $line ; } else { echo "Failed to flush data for line: " . $line ; } } ?> |
Output:
Data flushed successfully for line: Line 1: This is the first line of data.
Data flushed successfully for line: Line 2: This is the second line of data.
Data flushed successfully for line: Line 3: This is the third line of data.
Reference: https://www.php.net/manual/en/splfileobject.fflush.php