Showing posts with label fwrite(). Show all posts
Showing posts with label fwrite(). Show all posts

Monday 30 July 2012

PHP fwrite Function


PHP - File Write

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!
Below we are writing a couple of names into our test file testfile.txt and separating them with a carriaged return.

PHP Code:

$myFile = "testfile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "News Paper\n";
fwrite($fh, $stringData);
$stringData = "Note Book\n";
fwrite($fh, $stringData);
fclose($fh);
The $fh variable contains the file handle for testfile.txt. The file handle knows the current file pointer, which for writing, starts out at the beginning of the file.

We wrote to the file testfile.txt twice. Each time we wrote to the file we sent the string $stringData that first contained News Paper and second contained Note Book. After we finished writing we closed the file using the fclose function.