Tuesday, April 17, 2007

PHP - Create and Write to File

Create and Write to File

Let's use the 'a' mode to open/create our file. This will append any new data to the end of the file, but opens the file access for writing only. If the file does not exist, this mode will attempt to create it first:

$data = "This is a new file entry!\n";
$file = "newfile.txt";
if (!$file_handle = fopen($file,"a")) { echo "Cannot open file"; }
if (!fwrite($file_handle, $data)) { echo "Cannot write to file"; }
echo "You have successfully written data to $file";
fclose($file_handle);
?>

No comments: