Thursday, September 25, 2025
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
32319 POSTS0 COMMENTS
Milvus
84 POSTS0 COMMENTS
Nango Kala
6681 POSTS0 COMMENTS
Nicole Veronica
11854 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11910 POSTS0 COMMENTS
Shaida Kate Naidoo
6794 POSTS0 COMMENTS
Ted Musemwa
7070 POSTS0 COMMENTS
Thapelo Manthata
6753 POSTS0 COMMENTS
Umr Jansen
6761 POSTS0 COMMENTS