Wednesday, May 27, 2026
HomeLanguagesPHP SplFileObject fflush() Function

PHP SplFileObject fflush() Function

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

RELATED ARTICLES

Most Popular

Dominic
32514 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6892 POSTS0 COMMENTS
Nicole Veronica
12012 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12107 POSTS0 COMMENTS
Shaida Kate Naidoo
7016 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6975 POSTS0 COMMENTS
Umr Jansen
6963 POSTS0 COMMENTS