File Create – PHP Advanced

Create File – fopen( )

fopen( ) function is also used to create a file. In PHP, by same function to open file, a file is also created using that same function. It creates new file, given that file is opened for appending(a) or writting(w) when you use fopen( ) function on file that does not exist.

$myfile = fopen("example2.txt", "w")
//This will create a new file naming "example2" on same directory where the code resides.

Write to File -fwrite( )

It is used to write a file. Here,  first parameter of fwrite() contains name of file to write and second parameter is string to be written.

<?php
 $file = fopen("ex2.txt", "w") or die("Unable to open file!");
 $text = "Code\n";
 fwrite($file, $text);
 $text = "Projects\n";
 fwrite($file, $text);
 fclose($file);
 ?>

//This creates a text file containig the string $text that contains “Code” and “Projects”

OverWriting :

And now that “ex2.txt” contains some data we can show what happens when we open an existing file for writing. All existing data will be removed and we start with an empty file.

<?php
 $file = fopen("ex2.txt", "w") or die("Unable to open file!");
 $text = "Projects\n";
 fwrite($file, $text);
 $text = "Tutorial and More\n";
 fwrite($file, $text);
 fclose($file);
 ?>

//Now when we run the code, previous data will be erased and replaced by new data.

 

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x