Different Functions Used To Write File With Example In PHP

admin_img Posted By Bajarangi soft , Posted On 22-09-2020

In PHP write functions are used only to write in opens a file . If file not exist then new file is created and if file already exists then contents of file is erased and To write data into a file, you need to use w, r+, w+, x, x+, c or c+ mode.

How to write a file in PHP

PHP file write functions are given below:

  • fwrite()
  • fputs()
 

1.PHP fwrite() Function
The fwrite() writes to an open file.it will stop at the end of the file (EOF) or when it reaches the specified length.

Syntax for fwrite() Function

fwrite(file, string, length)


Parameter   Description

file     Specifies the open file to write to
string   Specifies the string to write to the open file
length   Specifies the maximum number of bytes to write


Example(1)
<?php
$file = fopen("myfile.txt","w");
echo fwrite($file,"Hello World. Welcome to bajarangisoft!");
fclose($file);
?>


2.PHP fputs() Function
The fputs() function is an alias of the fwrite() function.


Complete code of write file function.
<!DOCTYPE html>
<html>
<head>
    <title>What are the different functions used to write file in PHP</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>

<body>
<div class="container">
    <br>
    <br>
    <br>
    <div class="text-center">
        <h1>PHP Write a file in  different Function</h1>
    </div>
    <br>
    <br>
    <h2></h2>
    <div class="well">
        <?php
        $file = fopen("myfile.txt","w");
        echo "<h1>".fwrite($file,"Hello World. Welcome to bajarangisoft!")."</h1>";
        fclose($file);
        ?>
    </div>
    <br>
</div>
</body>
</html>

Related Post