Friday, September 5, 2025
HomeLanguagesPHP | SplFileObject fwrite() Function

PHP | SplFileObject fwrite() Function

The SplFileObject::fwrite() function is an inbuilt function of Standard PHP Library (SPL) in PHP which is used to write to the file.

Syntax:

int SplFileObject::fwrite( $str, $length )

Parameters: This function accept two parameters as mention above and describe below:

  • $str: It is used to specify the string which need to write to the file.
  • $length: It is an optional parameter. If it is given then file writing will stop after a specified length.

Return values: This function returns the number of bytes written to the file and 0 on error.

Below Programs illustrate the SplFileObject::fwrite() function in PHP:

Program 1:




<?php
  
// Create a file named "gfg.txt" if not exist
$gfg = new SplFileObject("gfg.txt", "w+");
  
// Write data in gfg.txt
$gfg->fwrite("neveropen a CS Portal");
  
// Open file again in read mode
$gfg = new SplFileObject("gfg.txt");
  
// Print result after written
while (!$gfg->eof()) {
    echo $gfg->fgetc();
}
?>


Output:

neveropen a CS Portal

Program 2:




<?php
   
// Create an Array
$GFG = array(
    "dummy.txt",
    "gfg.txt",
    "frame.txt"
    );
   
// Creating Spl Object
foreach ($GFG as &$arr) {
    $gfg = new SplFileObject($arr, "w+");
       
    // Write data in file
    $gfg->fwrite("neveropen a CS Portal for Geeks");
       
    // Open file again in read mode
    $gfg = new SplFileObject("gfg.txt");
       
    // Print result after written
    while (!$gfg->eof()) {
        echo $gfg->fgetc();
    }
      
    echo  "</br>";
}
?>


Output:

neveropen a CS Portal for Geeks
neveropen a CS Portal for Geeks
neveropen a CS Portal for Geeks

Reference: http://php.net/manual/en/splfileobject.fwrite.php

RELATED ARTICLES

Most Popular

Dominic
32269 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6636 POSTS0 COMMENTS
Nicole Veronica
11802 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11865 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7026 POSTS0 COMMENTS
Thapelo Manthata
6703 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS