How to re-write file contents in PHP?

How to overwrite file contents with new content in PHP?

For PHP developer must know How to overwrite a file if needed, To write data over file file_put_contents is to be used. This function is similar to calling fopen (), fwrite () & fclose () to write data to a file, respectively. In case if filename doesn’t exit file will be created itself, Otherwise it will create new one.

file_put_contents('file.txt', 'bar');
echo file_get_contents('file.txt'); // bar
file_put_contents('file.txt', 'foo');
echo file_get_contents('file.txt'); // foo

Alternatively, in case you’re left with fopen() you can utilize the w or w+ modes:

‘w’ Open for writing only; place the file pointer toward the start of the document and shorten the document to zero length. On the off chance that the fie doesn’t exist, endeavor to create it.

Where as ‘w+’ Open for reading and writing;

Note: Don’t forgot to allow permission to file/folder in which you are going create or rewrite your file.

Article you may like :

  1. API Tutorial For Beginners With Google Sheets
  2. How to access wordpress functions and database in custom php file

Author: Shantun Parmar

Leave a Reply

Your email address will not be published.