Open the text file for writing
In the same way as when reading from a text file, the fopen function is used for writing, but this time we set the mode to "w" (writing) or "a" (appending).The difference between writing and appending is where the 'cursor' is located - either at the beginning or at the end of the text file.
The examples in this lesson use an empty text file called textfile.txt. But you can also create your own text file if you like.
First, let us try to open the text file for writing:
<?php
// Open the text file
$f = fopen("textfile.txt", "w");
// Close the text file
fclose($f);
?>
Example 1: Write a line to the text file
<html>
<head>
<title>Writing to a text file</title>
</head>
<body>
<?php
// Open the text file
$f = fopen("textfile.txt", "w");
// Write text line
fwrite($f, "PHP is fun!");
// Close the text file
fclose($f);
// Open file for reading, and read the line
$f = fopen("textfile.txt", "r");
echo fgets($f);
fclose($f);
?>
</body>
</html>
Example 2: Adding a text block to a text file
<html>
<head>
<title>Write to a text file</title>
</head>
<body>
<h1>Adding a text block to a text file:</h1>
<form action="myfile.php" method='post'>
<textarea name='textblock'></textarea>
<input type='submit' value='Add text'>
</form>
<?php
// Open the text file
$f = fopen("textfile.txt", "w");
// Write text
fwrite($f, $_POST["textblock"]);
// Close the text file
fclose($f);
// Open file for reading, and read the line
$f = fopen("textfile.txt", "r");
// Read text
echo fgets($f);
fclose($f);
?>
</body>
</html>
No comments: