In this article, we are going to discuss how to write into a text file using the PHP built-in fwrite() function.
The fwrite() function is used to write into the given file. It stops at the end of the file or when it reaches the specified length passed as a parameter, whichever comes first. The file has to close by using the PHP fclose() function.
Syntax:
fwrite(file_name, string)
- file_name: The name of the input file
- string: The content to be written.
Return Value: It returns the number of bytes written on success, or false on failure.
Example 1: The code example below shows how to write a text to the “geeks_data.txt” file.
PHP
<?php
$data = fopen ( "geeks_data.txt" , "w" );
echo fwrite( $data , "This data is added as extra" );
fclose( $data );
?>
|
geeks_data.txt: When the user opens this text file, the following text content is found after opening it.
This data is added as extra
Output:
27
Example 2:
PHP
<?php
$data = fopen ( "geeks_data.txt" , "w" );
echo fwrite( $data , "This data is added as extra
along with previous data");
fclose( $data );
?>
|
geeks_data.txt: The following content is found after opening the file.
This data is added as extra
along with previous data
Output:
74
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
31 May, 2023
Like Article
Save Article