Friday, September 29, 2017

PHP Write File

PHP Write File

PHP fwrite() and fputs() functions are used to write data into file. To write data into file, you need to use w, r+, w+, x, x+, c or c+ mode.

PHP Write File - fwrite():
The PHP fwrite() function is used to write content of the string into file.

Syntax:
int fwrite ( resource $handle , string $string [, int $length ] )

Example:
<?php  
//opens file in write-only mode 
$fp = fopen('file.txt', 'w'); 
// writing data in file
fwrite($fp, 'welcome to skptricks ');  
fwrite($fp, 'writing data in file');  
//closing file
fclose($fp);    
echo "File written successfully";  
?>
Output:
-------------------------
welcome to skptricks
writing data in file

Note : If you run the above code again, it will erase the previous data of the file and writes the new data.

Let see the below example, here we are trying to overwrite the above existing file "file.txt". It will erase all the existing data and write new data.

Example :
<?php  
//opens file in write-only mode 
$fp = fopen('file.txt', 'w'); 
// writing data in file
fwrite($fp, 'welcome to skptricks ');   
//closing file
fclose($fp);    
echo "File written successfully";  
?>
Output:
-------------------------
welcome to skptricks


No comments:

Post a Comment