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.

function Write2TxtFile($fname, $textdata)
{
	$fstatus = file_put_contents($fname, $textdata);
	if (!$fstatus)
	{
		// Error - Cannot write to file.
		return false;
	} else
		return true;
}


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.

function Write2TxtFile($fname, $textdata)
{
	$fstatus = file_put_contents($fname, $textdata, FILE_APPEND);
	if (!$fstatus)
	{
		// Error - Cannot write to file.
		return false;
	} else
		return true;
}

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