We can use php to write to a text file. The fwrite function allows data to be written to any type of file. Fwrite's first parameter is the file handle and its second parameter is the string of data that is to be written. Just give the function those two bits of information and you're good to go
Example:
<?php
$filename = 'test.txt';
$somecontent = "Add this to the file\n";
// Let's make sure the file exists and is writable first.
if (is_writable($filename)) {
// In our example we're opening $filename in append mode.
// The file pointer is at the bottom of the file hence
// that's where $somecontent will go when we fwrite() it.
if (!$handle = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";
exit;
}
// Write $somecontent to our opened file.
if (fwrite($handle, $somecontent) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
echo "Success, wrote ($somecontent) to file ($filename)";
fclose($handle);
} else {
echo "The file $filename is not writable";
}
?>
Note: On systems which differentiate between binary and text files (i.e. Windows) the file must be opened with 'b' included in fopen() mode parameter.
2.fwrite() returns the number of bytes written, or FALSE on error.
handle:A file system pointer resource that is typically created using fopen().
String:The string that is to be written.
Length:
If the length argument is given, writing will stop after length bytes have been written or the end of string is reached, whichever comes first.
Note that if the length argument is given, then the magic_quotes_runtime configuration option will be ignored and no slashes will be stripped from string .
Note: If writing twice to the file pointer, then the data will be appended to the end of the file
Sunday, March 8, 2009
Writing a File PHP
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment