PHP Code Snippet - Write data to text file

PHP Code Snippet - Write data to text file

PHP Code Snippet - Write data to text file

PHP code snippet to write text data into a file using file_put_contents function. Write2TxtFile function writes text data to a given file. Function return TRUE if data successfully written to file, if not function will return FALSE.

Bookmark:

PHP Code Snippet - Write data to text file

This PHP code snippet writes text data to a given file. If file name does not exist, the file is created. Otherwise, the existing file is overwritten.

01function Write2TxtFile($fname, $textdata)
02{
03    $fstatus = file_put_contents($fname, $textdata);
04    if (!$fstatus)
05    {
06        // Error - Cannot write to file.
07        return false;
08    } else
09        return true;
10}


This function is similar to above, except if file name already exists, append the data to the file instead of overwriting it. This is done by passing FILE_APPEND flag to file_put_contents function.

01function Write2TxtFile($fname, $textdata)
02{
03    $fstatus = file_put_contents($fname, $textdata, FILE_APPEND);
04    if (!$fstatus)
05    {
06        // Error - Cannot write to file.
07        return false;
08    } else
09        return true;
10}

PHP Keywords Used:

  • file_put_contents
  • FILE_APPEND

Code Snippet Information:

  • Applies To: PHP, File Handling, IO
  • Programming Language : PHP (PHP 5+)

External Resources:

Vorleak :: June 23-2011 :: 01:54 AM

it is very nine. great example!!

Leave a comment

 Poster Information 


(will not be published, required)

 MESSAGE DETAILS