使用PHP替换文本文档中的特定字符串

I'm trying to make the user input form data and when hitting submit it places the form data in a existing text file and replaces the specific string with that form data.

<?php
$myFile = "freewill.doc";
$fh = fopen($myFile, 'a') or die("can't open file");
$fName = $_POST["fName"];
fwrite($fh, $fName);
$mInitial = $_POST["mInitial"];
fwrite($fh, $mInitial);
$lName = $_POST["lName"];
fwrite($fh, $lName);
$placeholders = array('fin', 'min', 'lana');

$namevals = array($fName,$mInitial,$lName);

echo "<br/>namevals 0:".$namevals[0];

$path_to_file = 'freewill.doc';
$file_contents = file_get_contents($path_to_file);
$file_contents = str_replace($placeholders,$namevals,$file_contents);

//build the string by putting each piece of text and variable exactly where 
you want it:
$string = "I, ".$fName." ".$mInitial." ".$lName.", a resident of Neverland 
County, Virginia, revoke any prior wills and amendments to wills made by me 
and declare this Will to be my Last Will and Testament.";

file_put_contents($path_to_file,$string);
fclose($fh);
?> 

This is something that I have already but all it does it build the string from the code and not actually inserting it into the file but rewriting the whole line. I need to go to another page when the user hits submit so the data needs to pass over and not replace what is already done but keep adding to it.

<h2>Please enter your name.</h2>
<form method="post" action="<?php echo 
htmlspecialchars($_SERVER["PHP_SELF"]);?>">  
First Name: <input type="text" name="fName">
<br><br>
Middle Initial: <input type="text" name="mInitial">
<br><br>
Last Name: <input type="text" name="lName">
<br><br>
<input type="submit" name="submit" value="Next"> 
<button type="button" onclick="location.href='download.php'">Download 
will</button>  
</form>

Here is my form data

Change the code as following:

$file_contents = str_replace($placeholders,$namevals,$file_contents);

// removed $string

file_put_contents($path_to_file,$file_contents);
fclose($fh);

The issue was you were writing $string to file instead of writing the $file_contents which was extracted from the file.