Writing Files

Open file, write string, close file

file_put_contents(file) ;

 

Returns number of bytes written upon success, or FALSE upon failure

<?php
	$fileName = "/home/d/newFile.txt" ;

	$myString = "Here's some text that I want to be written to a file";

	$bytesWritten = file_put_contents($fileName, $myString);

	echo "$bytesWritten bytes written";
?>

 

If filename does not exist, the file is created. Otherwise, the existing file is overwritten, unless the FILE_APPEND flag is set.

<?php
	$fileName = "/home/d/newFile.txt" ;

	$myString = "More text to append to the file";

	$bytesWritten = file_put_contents($fileName, $myString, FILE_APPEND);

	echo "$bytesWritten bytes written";
?>

 

Wite opened file

fwrite(file, string) ;

 

Returns number of bytes written upon success, or FALSE upon failure

<?php
	$fileName = "/home/d/myFile.txt" ; //specify file name

	$fileHandle = fopen($fileName,"w") ; //open above and assign to handle

	$myString = "Text being written to a file" ; //create string

	//write the string and assign the number of bytes written in the return value
	$bytesWritten = fwrite($fileHandle, $myString) ;

	fclose( $fileHandle ) ; //close file

	echo $bytesWritten ; //display contents
?>

Leave a Reply