当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


PHP SplFileObject fflush()用法及代码示例


SplFileObject::fflush()function 是 PHP 标准 PHP 库 (SPL) 中的内置函数,用于刷新文件的输出缓冲区。

用法:

public SplFileObject::fflush():bool

范围:该函数不接受任何参数。

返回值: SplFileObject::fflush()如果函数成功刷新文件的输出缓冲区,则函数返回“true”,否则,该函数将返回“false”。

程序1:下面的程序演示了SplFileObject::flush()函数。 “output.txt” 应位于同一文件夹中。

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."; 
} 
  
?>

输出:

Data flushed successfully to the file.

程序2:下面的程序演示了SplFileObject::flush()函数。 “output.txt” 应位于同一文件夹中。

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; 
    } 
} 
  
?>

输出:

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.

参考:https://www.php.net/manual/en/splfileobject.fflush.php



相关用法


注:本文由纯净天空筛选整理自neeraj3304大神的英文原创作品 PHP SplFileObject fflush() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。