Write to Text File in PHP

Write to text file in php - There are several functions in PHP that can be used to write files. Those functions are the fwrite() function, the fputs() function, the file_put_contents() function. To be able to write into a file, we have to open the file with w or a.
To better understand it, consider the following example program.
Program 1
File Name: file03.php
Description: Program write to file.
Open notepad then type the following php code.
<?php
$filename = "data.txt";
$handle = fopen ($filename, "w");
if(!$handle) {
 echo "<b>File can not be opened or not yet exists</b>";  } else {
 fwrite ($handle, "Faculty of Information Technology\n");
 fputs ($handle, "University of Jakarta\n");   //file_put_contents ($filename, "Jakarta");  
 echo "<b>The file was successfully written</b>"; 
 }
fclose($handle);
?>

Write to Text File in PHP

Save the code with file03.php in the htdocs folder.
Program Explanation 1
To write to a file, can use the function fwrite () and fputs (). The $ handle variable is a file access mode, where the mode used should be able to write to the file. For example w mode and a. In addition, we can also use the function file_puts_contents () with parameters of the file name and contents to be added. If the above program is executed, then the contents of data.txt file will contain as in the following picture (open with notepad ++).
To see the result run the program by opening the browser, then input this address http://localhost/file03.php in address bar then enter.
Write to Text File in PHP
Program view

Next open the file data.txt then in the file will appear posts according to commands in the code.
Write to Text File in PHP
Add caption

That's the article about write to text file in php. Hopefully these tutorials can add to our knowledge of php programming language.

Comments